Zustandのインストールと基本設定
🧱 1. シンプルな状態の作成
Zustandでは、create
関数を使って状態(store)を作成します。
この例では、count
という数値の状態と、それを増減させる increment
/ decrement
関数を定義しています。
// store.ts
import { create } from 'zustand'
type CounterState = {
count: number
increment: () => void
decrement: () => void
}
export const useCounterStore = create
<CounterState>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}))
🧩 2. Reactコンポーネントでの使用
作成した store は、useCounterStore()
フックを使って簡単にコンポーネントから利用できます。
状態の読み取り・更新は、useStateと同様に直感的に書けます。
// Counter.tsx
import React from 'react'
import { useCounterStore } from './store'
const Counter = () => {
const { count, increment, decrement } = useCounterStore()
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>+1</button>
<button onClick={decrement}>-1</button>
</div>
)
}
export default Counter
📌 ポイント
useState
と同様、状態を変更するとその値に依存しているコンポーネントが自動的に再レンダリングされます。
Zustandでは、どのstateを購読しているかに応じて、必要な箇所だけが効率的に更新されるため、パフォーマンス面でも優れています。
📌 useStateとの違い
useState
では親子コンポーネント間で状態を共有するにはpropsで渡す必要がありますが、
Zustandならstoreを直接インポートしてアクセスでき、状態の共有がとても簡単になります。
🎯 3. 特定のstateだけを購読する
Zustandは状態の一部だけを購読することが可能です。
そのため、状態の一部が変更されても、購読していない部分には影響がなく、再レンダリングされません。
// CounterLabel.tsx
import { useCounterStore } from './store'
const CounterLabel = () => {
const count = useCounterStore((state) => state.count)
return
<span>現在のカウント: {count}</span>
}
📌 ポイント
このように セレクタ関数(例:(state) => state.count
)を使うことで、必要な部分だけの購読ができ、アプリのパフォーマンスを最適化できます。