Immer lets you update an immutable collection using mutation-style code. Its `produce` function gives a callback a mutable-looking draft, then returns a modified copy of the original state. section 10.4.3
The draft is a Proxy, not the original object. Immer intercepts interactions with it and uses them to construct the updated copy. This avoids both shallow-copy bugs in nested data and the cost of deep-copying every object. section 10.4.3
Updating nested state
A TypeScript example uses `produce` to add a ninja to a read-only state’s array and update its Map. The callback can mutate the draft while the original state remains the input to the update. section 10.4.3
Listing 10.15 Applying mutations to an immutable object with Immer
import { enableMapSet, produce } from "immer";
enableMapSet(); #A
interface NinjaMetadata {
homeIsland: string;
}
type NinjaState = Readonly<{ #B
ninjas: ReadonlyArray<string>; #B
ninjaMetadata: ReadonlyMap<string, NinjaMetadata>; #B
lastModified: number; #B
}>; #B
const initialState: NinjaState = { #C
ninjas: ["Kuma", "Hattori", "Yagyu"], #C
ninjaMetadata: new Map( #C
Object.entries({ #C
Kuma: { homeIsland: "Honshu" }, #C
Hattori: { homeIsland: "Hokkaido" }, #C
}), #C
), #C
lastModified: Date.now(), #C
}; #C
const getStateWithNewNinja = (
previousState: NinjaState,
newNinja: string,
newNinjaMetadata: NinjaMetadata,
): NinjaState => {
return produce(previousState, (state) => { #D
state.ninjas.push(newNinja); #D
state.ninjaMetadata.set(newNinja, newNinjaMetadata); #D
state.lastModified = Date.now(); #D
}); #D
};
const nextState = getStateWithNewNinja( #E
initialState, #E
"Yoshi", #E
{ homeIsland: "Yoshi's Island" }, #E
); #E
console.assert(
nextState.ninjas.length ===
initialState.ninjas.length + 1,
"Added a new ninja",
);
console.assert(
nextState.ninjaMetadata.size ===
initialState.ninjaMetadata.size + 1,
"Added metadata for the new ninja",
);
See the TypeScript example using `produce` with a read-only state, an array, and a Map. section 10.4.3

