ドキュメント
はじめに
インストール
npm または yarn を使用して Zustand をインストールします:
npm install zustand # or yarn add zustand # or pnpm add zustand最初のストア
Store の作成は簡単です。これはシンプルなカウンターの例です:
import { create } from 'zustand'
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
}))基本的な使い方
React コンポーネントで store を使用します:
function Counter() {
const count = useStore((state) => state.count)
const increment = useStore((state) => state.increment)
const decrement = useStore((state) => state.decrement)
const reset = useStore((state) => state.reset)
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
)
}コアコンセプト
ストア
Store はアプリケーションの状態を保持します。`create` 関数を使用して作成され、React フックを返します。
状態
状態は store が保持するデータです。オブジェクト、配列、プリミティブなど、任意の JavaScript 値を使用できます。
アクション
アクションは状態を変更する関数です。`set` 関数を使用して store を更新します。
セレクター
セレクターを使用すると、状態の特定の部分を購読して、再レンダリングを最適化できます。