zustandとは
ZustandはReactのための軽量でシンプルな状態管理ライブラリ
set up
npm install zustand
使い方
storeの作成
import create from 'zustand'
// カウンターストアの定義
const useCounterStore = create(set => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 })),
decrement: () => set(state => ({ count: state.count - 1 })),
}))
コンポーネントでのストアの使用
import React from 'react'
import { useCounterStore } from './store' // ストアをインポート
const CounterComponent = () => {
const { count, increment, decrement } = useCounterStore()
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
)
}
export default CounterComponent
globalにならないようにpageごとにstateを管理する。
子コンポーネントへのstateの受け渡しはContext APIを使用する
例
Recipes