useReducer, don't useState
Published ....
Last modified ....
Share this post on BlueskySee discussion on Bluesky
This blog post assumes you have a decent initial understanding of React Hooks. I highly suggest starting with the ReactJS Docs on them first.
As developers start adopting React Hooks within their applications, many will be
tempted to start with useState as their state management preferences for local
component state. However, I would like to try an convince you that useReducer
is a better way to manage local state.
Lets start of with defining "better" in my premise from above, the definition I will use for this article will be that its:
- Easier to manage larger state shapes
- Easier to reason about by other developers
- Easier to test
So lets break down each of these three points.
Easier to manage larger state shapes
As with most of this blog post, this is mostly my opinion, however because
useState no longer shallowly merges state updates like it does within classes,
using a reducer function gives you the developer more control over the state
merging.
As an example of this expresivity that a reducer gives us, we can useReducer
to implement an undo/redo state management solution: