Skip to content

Instantly share code, notes, and snippets.

@BrianCodeItUp
Last active August 27, 2020 07:12
Show Gist options
  • Save BrianCodeItUp/2fb0c81b30096e6f72f5460aeb84aa15 to your computer and use it in GitHub Desktop.
Save BrianCodeItUp/2fb0c81b30096e6f72f5460aeb84aa15 to your computer and use it in GitHub Desktop.
custom react-redux connect using hook
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;
};
}
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)
@BrianCodeItUp
Copy link
Author

BrianCodeItUp commented Jun 16, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment