React & Immer
#
useState + ImmerThe 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.
#
useImmerSince 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 produce
automatically:
For the full demo see CodeSandbox.
#
useReducer + ImmerSimilarly to useState
, useReducer
combines neatly with Immer as well, as demonstrated in this CodeSandbox:
#
useImmerReducer...which again, can be slightly shorted by useImmerReducer
from the use-immer
package (demo):
#
Redux + ImmerRedux + 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!
For example: