Reputation: 1523
So we recently decided to start using hooks in our current react app. We are using redux for state management and my question was how does this work with hooks?
I've read some articles where people use the context api with hooks to create a state manager but I would like to keep using redux for now.
I know the react api has a useReducer
method, can this be used to dispatch redux actions? I've been looking for a tutorial/example but can't seem to find any resources online for this. I may be headed down the wrong path but would like to know if I am. Thanks.
Upvotes: 1
Views: 1497
Reputation: 3709
Nothing changes with hooks when using Redux, Redux Higher Order Component has nothing to do with Hooks. useReducer
isn't meant for dispatching Redux actions but for updating the component internal state the same way Redux does.
So when you use useReducer
you will dispatch actions, update the state with a reducer etc. but not the Redux state! Instead, you're doing that with the component state.
A component that consumes useReducer
is a standard component with an internal state (to manage input states or whatever you want) wrapped, as usual before the hooks born, in a Redux's connect HOC.
If it could be helpful you can clarify your ideas with this post
Upvotes: 2
Reputation: 16754
I'm not a heavy user of the Redux
(I prefer MobX
), so I might be overlooking certain subtle aspects. But from what I see it's pretty straightforward and React docs on hooks provide very nice example:
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter({initialState}) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
);
}
Instead of reducer
here, you can simply use one of the related reducers from your existing state management code base. Simply import it into the component file and pass it to the useReducer
as the first argument. The state that you will return from there will become a new state for the component and it will auto-rerender itself with it. Obviously you will need to disconnect such component from Redux
(if it is connected). Otherwise as it was mentioned in one of the comments you will end up with redundant state management logic.
However on your place I wouldn't rewrite it for hooks without any utter necessity.
Upvotes: 1