API Reference

create()

Creates a store with the given state creator function.

import { create } from 'zustand'

const useStore = create((set, get, api) => ({
  // state
  count: 0,
  // actions
  increment: () => set((state) => ({ count: state.count + 1 })),
}))

Parameters

  • stateCreator - Function that receives set, get, and api

Returns

A React hook that can be used to access the store

set()

Updates the store state. Can be called with a partial state object or an updater function.

// Partial update
set({ count: 1 })

// Updater function
set((state) => ({ count: state.count + 1 }))

// Replace entire state (not recommended)
set({ count: 0 }, true)

Parameters

  • partial - Partial state object or updater function
  • replace - (optional) Replace entire state instead of merging

get()

Gets the current state. Useful in actions or outside of React components.

const useStore = create((set, get) => ({
  count: 0,
  double: () => {
    const currentCount = get().count
    set({ count: currentCount * 2 })
  }
}))

subscribe()

Subscribe to state changes. Called whenever the state updates.

const unsubscribe = useStore.subscribe(
  (state) => console.log('State changed:', state)
)

// Later...
unsubscribe()

Middleware

persist()

Persists store state to localStorage or sessionStorage.

import { create } from 'zustand'
import { persist } from 'zustand/middleware'

const useStore = create(
  persist(
    (set) => ({
      count: 0,
      increment: () => set((state) => ({ count: state.count + 1 })),
    }),
    {
      name: 'counter-storage',
    }
  )
)

devtools()

Enables Redux DevTools integration for debugging.

import { create } from 'zustand'
import { devtools } from 'zustand/middleware'

const useStore = create(
  devtools((set) => ({
    count: 0,
    increment: () => set((state) => ({ count: state.count + 1 })),
  }))
)

immer()

Enables Immer for easier immutable updates.

import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'

const useStore = create(
  immer((set) => ({
    todos: [],
    addTodo: (text) =>
      set((state) => {
        state.todos.push({ id: Date.now(), text })
      }),
  }))
)

Selectors

Select specific parts of state to optimize re-renders.

// Select entire state
const state = useStore()

// Select specific property
const count = useStore((state) => state.count)

// Select with transformation
const doubled = useStore((state) => state.count * 2)

// Multiple selectors
const count = useStore((state) => state.count)
const increment = useStore((state) => state.increment)