DEV Community

loading...

Discussion on: useReducer instead of useState while calling APIs!

Collapse
jharteaga profile image
Jose Arteaga

Great post! it helped a lot to understand much better useReducer. Now, I'll try to put it into practice to remember its usage. Just quick question. Can I have more than one useReducer inside the Function Component? Because in the example there is just one and you call the dispatch method, however if you have more than one useReducer, how I can make the difference which I am working with? Thanks!!

Collapse
antontsvil profile image
Anton T

To help understand hooks, you might wanna look up array destructuring (similar to object destructuring). In short - you can use whatever names you like when destructuring an array, so just use different names for your second useReducer hook!

const [state, dispatch] = useReducer(userDetailsReducer, initialState);
const [likeState, likesDispatch] = useReducer(userLikesReducer, initialLikesState);
Enter fullscreen mode Exit fullscreen mode
Collapse
jharteaga profile image
Jose Arteaga

Thanks @antontsvil ! That helped me as well to understand that it is possible! great example!

Collapse
bpitts8019 profile image
Bradley Pitts

While it is possible to use more than one useReducer for the state of a component. I would recommend against it as each use of the useReducer hook will return it's own state object and dispatcher. Instead design the single reducer to control the whole state of the component. Any defined action in the reducer should return the whole state of the component with any expected updates as per that defined action.

Collapse
jharteaga profile image
Jose Arteaga

Very clear your explanation Bradley, got it! Thanks so much!

Some comments have been hidden by the post's author - find out more

Forem Open with the Forem app