Last active
August 27, 2020 07:12
-
-
Save BrianCodeItUp/2fb0c81b30096e6f72f5460aeb84aa15 to your computer and use it in GitHub Desktop.
custom react-redux connect using hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useSelector, useDispatch } from 'react-redux' | |
function connect(mapStateToProps, mapDispatchToProps) { | |
return Component => { | |
const Wrapper = props => { | |
const seletedState = useSelector(state => mapStateToProps(state, props)); | |
const dispatch = useDispatch(); | |
const boundDispatch = mapDispatchToProps(dispatch, props); | |
return <Component {...seletedState} {...boundDispatch} {...props} />; | |
}; | |
return Wrapper; | |
}; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import connect from 'where your connect located' | |
import Component from 'where your component located' | |
const mapStateToProps = (state, ownProps) => { | |
return { | |
// ...select data from store like the old ways | |
}; | |
}; | |
const mapDispatchToProps = (dispatch, ownProps) => ({ | |
fetch(param) { | |
dispatch({ type: 'ACTION_NAME', payload: param }) | |
}, | |
}); | |
export default connect(mapStateToProps, mapDispatchToProps)(Component) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The reason why i create a custom connect is because i want to preserve the container pattern. Container pattern keep component pure and easy to test with unit test and storybook. You may say: why don't just use the original
connect
method provided by react-redux. Here is the thing, the old method will recreate dispatch function everytime store get update. But when i call these boundDispatch methods in useEffect, i have to put them into dependencies. So if store get updated, useEffect will run again which is not what i want.