egghead.io lesson 3: Simplifying deep updates with _produce_
Hosted on egghead.io
The Immer package exposes a default function that does all the work.
produce(baseState, recipe: (draftState) => void): nextState
produce takes a base state, and a recipe that can be used to perform all the desired mutations on the
draft that is passed in. The interesting thing about Immer is that the
baseState will be untouched, but the
nextState will reflect all changes made to
draft object, including field assignments,
delete operations, and mutating array, Map and Set operations like
Any of those mutations don't have to happen at the root, but it is allowed to modify anything anywhere deep inside the draft:
draft.todos.tags["urgent"].author.age = 56
Note that the recipe function itself normally doesn't return anything. However, it is possible to return in case you want to replace the
draft object in its entirety with another object, for more details see returning new data.
(base)state, the immutable state passed to
recipe: the second argument of
produce, that captures how the base state should be "mutated".
draft: the first argument of any
recipe, which is a proxy to the original base state that can be safely mutated.
producer. A function that uses
produceand is generally of the form
(baseState, ...arguments) => resultState
Note that it isn't strictly necessary to name the first argument of the recipe
draft. You can name it anything you want, for example
draft as a name is just a convention to signal: "mutation is OK here".