Skip to content
D
Documentation

Immutable state and merging

concept
2 min readUpdated

Immutable updates create new references for changed state, while Zustand's one-level merge preserves the top-level fields you leave out.

Use create to bind a store to a React hook. Inside its initializer, set updates that store; outside it, the returned hook exposes setState() with the same merging and replacement behavior.

How an update works

Pass set an object or an updater function. An updater receives the current state and returns the next state or a partial update. For an object update, the default merge creates a new top-level state object using the existing fields followed by your update. You do not need to spread the whole state yourself.

mermaid
flowchart TD
  A["Object or updater passed to set"] --> B["Compute next state"]
  B --> C{"Object.is(nextState, currentState)?"}
  C -->|Yes| D["No notification"]
  C -->|No| E{"replace is true?"}
  E -->|Yes| F["Use next state directly"]
  E -->|No, object update| G["Shallow merge with current state"]
  F --> H["Notify subscribers"]
  G --> H

The same-reference check happens before merging. Returning the existing state object does not notify subscribers. Nested objects also need new references when they change: mutating an existing object, Map, or Set leaves its reference unchanged. Copy each changed object level, preserve its other fields explicitly, and create new Map or Set instances when updating collections. See Update Maps and Sets for collection operations.

One-level merging and nested objects

Start from the project in the React quick start, with Zustand installed. Keep the starter's entry file, including its mounting code and stylesheet imports. The following two files supply its App component and the replacement example used below.

Add src/ReplaceExample.tsx from the next section, then update src/App.tsx:

tsx
import { create } from 'zustand'
import { ReplaceExample } from './ReplaceExample'

type CounterStore = {
  count: number
  nested: { count: number; label: string }
  increment: () => void
  incrementNested: () => void
}

const useCounterStore = create<CounterStore>()((set) => ({
  count: 0,
  nested: { count: 0, label: 'Nested counter' },
  increment: () => set((state) => ({ count: state.count + 1 })),
  incrementNested: () =>
    set((state) => ({
      nested: { ...state.nested, count: state.nested.count + 1 },
    })),
}))

export default function App() {
  const count = useCounterStore((state) => state.count)
  const nested = useCounterStore((state) => state.nested)
  const increment = useCounterStore((state) => state.increment)
  const incrementNested = useCounterStore((state) => state.incrementNested)

  return (
    <main>
      <h1>Immutable updates</h1>
      <p>Top-level count: {count}</p>
      <button onClick={increment}>Increment top-level count</button>
      <p>{nested.label}: {nested.count}</p>
      <button onClick={incrementNested}>Increment nested count</button>
      <ReplaceExample />
    </main>
  )
}

Both counts start at zero. Increment top-level count changes only count: the merge preserves nested and both actions without a top-level spread. Increment nested count creates a new nested object and changes its count, while the explicit ...state.nested preserves the label “Nested counter.”

set does not recursively merge objects. For deeper nesting, spread every object along the path to the changed value; leave unchanged branches alone. For an alternative to manual nested copies, see Update state with Immer.

Replace flag

Use replacement when the supplied value represents the whole next state rather than a partial update. This example keeps its update controls outside the store and displays which fields remain after replacement.

  1. Add this component. Its store starts with a count and an optional note.
  2. Run the app using the quick start's development command. Click Merge increment to retain the note, then Replace with count only to remove it while increasing the count.
tsx
import { create } from 'zustand'

type ReplacementState = {
  count: number
  note?: string
}

const useReplacementStore = create<ReplacementState>()(() => ({
  count: 0,
  note: 'Initial note',
}))

export function ReplaceExample() {
  const count = useReplacementStore((state) => state.count)
  const note = useReplacementStore((state) => state.note)

  return (
    <section>
      <h2>Replace flag</h2>
      <p>Count: {count}</p>
      <p>Note: {note ?? 'No note in state'}</p>
      <button
        onClick={() =>
          useReplacementStore.setState((state) => ({
            count: state.count + 1,
          }))
        }
      >
        Merge increment
      </button>
      <button
        onClick={() =>
          useReplacementStore.setState(
            (state) => ({ count: state.count + 1 }),
            true,
          )
        }
      >
        Replace with count only
      </button>
    </section>
  )
}

The merge button preserves “Initial note.” The replacement button supplies the complete next state, { count: ... }, and the view displays “No note in state.” The same second argument works with set inside an action.

replace valueTypeDefaultWhat it does
OmittedundefinedOmittedShallowly merges object updates; replaces primitive or null updates.
falseboolean—Explicitly requests shallow merging.
trueboolean—Uses the supplied next state directly, without merging.

The replacement overload requires a complete state value, or an updater returning one. Here note is optional, so a count-only value is complete. See Type stores and selectors for complete-state replacement typing and stores that contain actions.

Was this page helpful?