Using the functional updates pattern with React hooks
The functional updates pattern can be used whenever you need to update state using the previous state.
For example, if you were storing in state the number of times a button was clicked, you might do it by referring to the previous count
state:
Instead of doing count + 1
, you can pass in a function to setCount
:
What’s the benefit of using functional updates?
In the above example, there’s no immediate benefit to using this pattern (that I know of). However if you were setting state inside of a useEffect
hook:
Since count
is a dependency, each time count
was changed by setCount
, useEffect
would be called again causing an infinite number of re-renders.
Using the functional updates pattern in this case makes sense:
If you have any better use cases that you can think of, I’d love to hear about them!
Thanks for reading!
References
https://reactjs.org/docs/hooks-reference.html#functional-updates