Installation
In order to use the Immer middleware in Zustand, you will need to install Immer as a direct dependency.Usage
Notice the extra parentheses after the type parameter as mentioned in the TypeScript Guide.
Updating Simple States
For simple state updates, Immer allows you to directly mutate the state object:Updating Complex States
Immer really shines when working with deeply nested or complex state structures:Gotchas
In this section you will find some things that you need to keep in mind when using Zustand with Immer.My subscriptions aren’t being called
If you are using Immer, make sure you are actually following the rules of Immer. If you don’t do this, Immer will still mutate the object, but not as a proxy, so it will also update the current state. Zustand checks if the state has actually changed, so since both the current state and the next state are equal (if you don’t do it correctly), Zustand will skip calling the subscriptions.Live Demos
Basic Example
Simple counter example using Immer middleware
Advanced Example
Complex todo list with nested state updates