liveBook · Manning

Immer

As explained in React in Depth

Immer is a JavaScript library that lets code express immutable state updates through drafts that can be modified directly.

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.
figure

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

How React in Depth covers it

How deep it goes
Explains draft mutation, proxy-based change recording, and immutable playback, but stops short of detailing the implementation internals.
Examples
Demonstrates updating a nested done array with manual copying and then with produce().
What it assumes
Assumes familiarity with reducers, immutable updates, nested JavaScript objects, and React state management.
What you can do after
Apply it via produce() to write reducers that mutate drafts while returning immutable state updates.
How it connects
Connects immutable state, reducers, React context, useReducer, and Zustand through alternative data-management patterns.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.