Immer lets reducers express immutable state updates with direct-looking mutations. It wraps a draft object, records changes, and produces an immutable alteration of the original state, reducing the ceremony of nested updates. section 8.4.1
Immer is most useful when immutable updates become difficult to maintain:
- Nested arrays and objects otherwise require copying every container along the update path. section 8.4.1
- The produce() function turns a reducer-style callback into an immutable update. section 8.4.1
- Zustand can apply Immer as middleware, avoiding a separate produce() wrapper around each function. section 8.6.1
Updating a nested array
import produce from 'immer'; doThing: produce((draft, { payload: id }) => { const thing = draft.things.find(thing => thing.id === id); thing.done.push(Date.now()); }) The callback mutates the draft directly, while Immer applies the change immutably to the resulting state. section 8.4.1
Figure 8.14 We need to modify the innermost array in this nested structure, where the array resides inside an object inside an array inside an object.
Inspect the nested structure to see why a small inner-array change requires copying several surrounding objects and arrays without Immer. section 8.4.1
