egghead.io lesson 8: Using Immer with _useState_. Or: _useImmer_
Hosted on egghead.io
useState hook assumes any state that is stored inside it is treated as immutable. Deep updates in the state of React components can be greatly simplified as by using Immer. The following example shows how to use
produce in combination with
useState, and can be tried on CodeSandbox.
Since all state updaters follow the same pattern where the update function is wrapped in
produce, it is also possible to simplify the above by leveraging the use-immer package that will wrap updater functions in
For the full demo see CodeSandbox.
useReducer combines neatly with Immer as well, as demonstrated in this CodeSandbox:
...which again, can be slightly shorted by
useImmerReducer from the
use-immer package (demo):
Redux + Immer is extensively covered in the documentation of Redux Toolkit. For Redux without Redux Toolkit, the same trick as applied to
useReducer above can be applied: wrap the reducer function with
produce, and you can safely mutate the draft!