Readers, if you're using Redux in a React project, you have to try these react-redux hooks. You will love them!
Look at the old way:
const UserComponent = (props) => {
return (
<div>
{props.profile.name}
</div>
)
}
function mapStateToProps(state) {
return {
profile: state.userReducer.profile,
auth: state.authReducer.auth
}
}
export default connect(mapStateToProps)(UserComponent);
And the hooks way:
import { useSelector } from 'react-redux';
const UserComponent = (props) => {
const profile = useSelector(state => state.userReducer.profile);
const auth = useSelector(state => state.authReducer.auth);
return (
<div>
{props.profile.name}
</div>
)
}
export default UserComponent;
The same goes for dispatching an action.
Before hooks:
const UserComponent = (props) => {
const login = () => {
props.login();
}
return (
<div>
{props.profile.name}
</div>
)
}
function mapStateToProps(state) {
return {
profile: state.userReducer.profile,
auth: state.authReducer.auth
}
}
function mapDispatchToProps(dispatch) {
return {
login: () => dispatch(userActions.login),
logout: () => dispatch(userActions.logout),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(UserComponent);
After:
import { useSelector, useDispatch } from 'react-redux';
import userActions from './actions';
const UserComponent = (props) => {
const profile = useSelector(state => state.userReducer.profile);
const auth = useSelector(state => state.authReducer.auth);
const dispatch = useDispatch();
const login = () => {
dispatch(userActions.login);
}
return (
<div>
{props.profile.name}
</div>
)
}
export default UserComponent;
You HAVE to try these hooks! That's all. Enjoy your weekend 😀😀
Top comments (7)
Glad you like them! Also, please check out our new official Redux Toolkit package. It includes utilities to simplify several common Redux use cases, including store setup, defining reducers, immutable update logic, and even creating entire "slices" of state at once:
redux-toolkit.js.org
Oh interesting, I'm taking a look now. Thanks 😊
I'm with ya. When using React I enjoy using hooks (with or without redux) much more than the old way. Based on my experience with both, hooks are easier to use and less code to write.
Oh man. I'm excited to utilize these ASAP!!!
This is great. I put off Redux for such a long time due to class component patterns.
Hooks just makes things so much better to work with. Now I’m going to enjoy working with Redux with the hooks options.
Thanks for the write up!
You're welcome, I'm glad you liked it ☺️
I did a refactoring to use this all over my project :)