useState, Zustand requires state updates to be immutable. Understanding how set merges state is crucial for working with Zustand effectively.
Basic State Updates
Here’s a typical example of updating state:Automatic Shallow Merging
Because state is immutable, updates should look like this:set automatically performs shallow merging, so you can skip the spread operator:
The
set function automatically merges the partial state object with the current state at the top level. You only need to return the properties you want to update.Nested Objects
When working with nested objects, you need to manually merge nested properties:Example with Multiple Nesting Levels
The Replace Flag
To disable the automatic merging behavior, specifytrue as the second parameter to set:
When to Use Replace
- Merging (Default)
- Replacing
Comparison with React’s setState
Key Takeaways
Shallow Merge
set automatically merges at the top level—you don’t need the spread operator for root propertiesNested Objects
Nested objects require manual spreading—automatic merging only works one level deep
Replace Flag
Use
set(newState, true) to completely replace the store instead of mergingImmutability
Always return new objects—never mutate existing state directly
Next Steps
For complex use cases with deeply nested objects, check out:- Updating State - Learn about helpers for deeply nested updates
- Immer Middleware - Simplify immutable updates with Immer