If you have been using Redux, and wonder how it can be used with React Hooks, this is how it is done:
Traditionally, this is how a component is connected to the Redux store:
import React from 'react'; import { connect } from 'react-redux'; function Count(props) { return ( <div> <button onClick={props.increment}> + </button> {props.count} <button onClick={props.decrement}> - </button> </div> ); } const mapStateToProps = state => ({ count: state.count }); const mapDispatchToProps = dispatch => ({ increment: () => dispatch({ type: 'INCREMENT' }), decrement: () => dispatch({ type: 'DECREMENT' }) }); export default connect(mapStateToProps, mapDispatchToProps)(Count);
Note that the Count
component gets the state and the dispatch functions by props
. But now, using React Hooks, we can get them by using useSelector()
and useDispatch()
:
import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; function Count() { const count = useSelector(state => state.count); const dispatch = useDispatch(); const increment = () => dispatch({ type: 'INCREMENT' }); const decrement = () => dispatch({ type: 'DECREMENT' }); return ( <div> <button onClick={increment}> + </button> {count} <button onClick={decrement}> - </button> </div> ); } export default Count;
That's it. useSelector()
is similar to mapStateToProps()
, and useDispatch()
is similar to mapDispatchToProps()
. All the other files stay the same, and that's how you can use Redux using React Hooks.
We can think of it this way:
- there are two things we need
- if we don't have redux, but just a React component, we are familiar with the fact that we need (1) the state to display the data, and (2) we need a callback to make the change of state to happen.
- Now, with Redux, similarly, we need:
- (1) is the state from the "one and only store", which is the redux store
- (2) we need a dispatch function to dispatch an action, so that the reducer can create a brand new shiny state for us
- so we can get the state by
useSelector()
- and we can get the
dispatch
function byuseDispatch()
- and then, the rest will follow: we have the state to display, and we have the mechanism to change the state if there is a need, using the
dispatch()
.
For further details, check out the official Redux Hooks page.
Top comments (0)