Hooks useReducer
useReducer
One hook I sometimes use is useReducer
.
This hook is used to manage state. Sort of like useState
, except more complex.
This is the key difference between useState
and useReducer
: with useReducer
, state is altered by passing messages rather than calling the updater function.
If you know how Redux works, that’s basically the same. A reducer is a pure function that calculates the next state based on the previous state and the action that has been dispatched.
What does “pure function” mean? A pure function takes an input and returns an output without changing the input or anything else. This means that a reducer returns a completely new state that substitutes the previous one.
A reducer should:
never mutate its arguments
never generate side-effects (no API calls changing anything)
never call non-pure functions, functions that change their output based on factors other than their input (e.g.
Date.now()
orMath.random()
)
There is no reinforcement, but you should stick to the rules. And this has a nice benefit: reducers are much simpler to test, because they have no side effects.
This allows to centralize the state management, allowing components to modify it by sending messages, and also allows you to use (and alter) a more complex state in your components.
Let’s do an example, with a counter component.
useReducer
accepts as arguments a reducer function, and an initial state value. In this case our state is an integer, which starts from 0:
The reducer is a function that takes, as explained above, the current state and an action, which can be a value of any type you want. In this case it’s a string:
We also make the component output some JSX to make this simple app work:
Here is the full example on
Now, imagine this state can be an object with many many properties, and different actions only change one property at a time. That’s a great use case for this hook.
Last updated