08/06/2023
When to use useReducer?
Oh, you will feel it. I know it’s a very weird answer, but that’s how it is 😱
I get this question very often, because sometimes programmers are a bit afraid of using useReducer. It looks complicated and defining reducer function stresses them out 🤪🤯 I really don’t know why 😅
In reality that’s not so complicated. Syntax is very similar to useState, but in this case you should provide a function, that will calculate state, depending on passed action.
📚 const [yourState, dispatch] = useReducer(functionToCalculateState, initialState);
You can look at useReducer hook as a set of instructions of how your state will change depending on actions :
action ➡️ result
For example:
loading ➡️ showing user that data is loading, hiding error messages, data is empty…
loaded ➡️ showing user loaded data
failure ➡️ showing error messages
For calculating new state we need to define a function, that gets the current state, action and returns the new state. To call reducer function you a have a setter - dispatch.
✅ dispatch({type: „yourAction“});
That’s all, you just need to experiment with useReducer and you will see how amazing this hook is.
Still, I recommend starting with useState, and when you feel that it’s becoming uncomfortable to manage state through multiple setState setters, then you must try useReducer. But it is important to try both variants to feel the difference.
Keep coding and having fun 🤩
#программирование