API リファレンス

create()

指定された状態作成関数でストアを作成します。

import { create } from 'zustand'

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

パラメータ

  • stateCreator - set、get、api を受け取る関数

戻り値

ストアにアクセスするために使用できる React フック

set()

ストアの状態を更新します。部分的な状態オブジェクトまたは更新関数で呼び出すことができます。

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

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

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

パラメータ

  • partial - 部分的な状態オブジェクトまたは更新関数
  • replace - (オプション)マージする代わりに状態全体を置き換える

get()

現在の状態を取得します。アクション内や React コンポーネントの外部で役立ちます。

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

subscribe()

状態の変更を購読します。状態が更新されるたびに呼び出されます。

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

// Later...
unsubscribe()

ミドルウェア

persist()

ストアの状態を localStorage または 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()

デバッグ用の Redux DevTools 統合を有効にします。

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

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

immer()

より簡単な不変更新のために Immer を有効にします。

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 })
      }),
  }))
)

セレクタ

再レンダリングを最適化するために状態の特定の部分を選択します。

// 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)