Course contentsShow
← React
Lesson 1712 of 2,39641. State Management EcosystemFree lesson

The set Function: Merging and Replacing

Understanding set's shallow merge behavior and how to use replace mode for full updates.

The set Function: Merging and Replacing

What you'll learn: How Zustand's set function updates state and when to use merge vs. replace mode.

The Default: Shallow Merge

When you call set in a Zustand store, it shallow merges by default. This means it spreads your existing state and overwrites only the properties you specify—just like setState in class components or spreading objects manually.

const useStore = create((set) => ({
  user: { name: 'Alice', age: 30 },
  theme: 'dark',
  
  updateName: (name) => set({ user: { name } })  // ⚠️ Problem!
}))

The trap: This shallow merge replaces the entire user object! You'd lose the age property. You need to manually spread nested objects:

updateName: (name) => set((state) => ({
  user: { ...state.user, name }
}))

Replace Mode: Starting Fresh

Sometimes you want to replace the entire state, not merge. Pass true as the second argument:

reset: () => set(
  { user: null, theme: 'light' },
  true  // Replace entire state
)

Analogy: Merge mode is like editing a document—you change specific words but keep the rest. Replace mode is deleting the file and creating a new one.

When to Use Each

  • Merge (default): Most updates—changing individual properties while preserving others
  • Replace: Reset functions, loading new data that represents a complete new state

Key Takeaway: Zustand's set shallow merges by default, so manually spread nested objects; use set(newState, true) to completely replace state instead of merging.