zustandとは
小さく、シンプルに管理することができる状態管理ライブラリのこと。
シンプルにコードを書くことができて、グローバルに保持することが可能。どのコンポーネントからもアクセスできます。
インストール方法
// yarnの場合
$ yarn add zustand
// npmの場合
$ npm install zustand
使い方
状態を管理するuseStoreフックを作成します。
create関数内で定義していき、set関数を使用して状態を変更します。
import create from "zustand";
type Count = {
count: number;
increaseCount: () => void;
decreaseCount: () => void;
resetCount: () => void;
}
export const useStore = create<Count>((set) => ({
count: 0,
increaseCount: () => set(state => ({ count: state.count + 1 })),
decreaseCount: () => set(state => ({ count: state.count - 1 }))
resetCount: () => set({ count: 0 }),
}));
useStore
をimportし、必要なstateのみ呼び出す。
useStore()
とするとすべてのstateを呼び出すことが可能だが、変更があるたびに再レンダリングされてしまうため注意が必要。
import type { NextPage } from "next";
import { useStore } from "../libs/store";
import styles from "../styles/Home.module.css";
const Count = () => {
const count = useStore((state) => state.count);
return (
<>
<h2>count: {count}</h2>
</>
);
};
const IncreaseCount = () => {
const increaseCount = useStore((state) => state.increaseCount);
return (
<>
<button onClick={() => increaseCount()}>Increase</button>
</>
);
};
const DecreaseCount = () => {
const decreaseCount = useStore((state) => state.decreaseCount);
return (
<>
<button onClick={() => decreaseCount()}>Decrease</button>
</>
);
};
const ResetButton = () => {
const { resetCount } = useStore();
return <button onClick={() => resetCount()}>Reset</button>;
};
const Home: NextPage = () => {
return (
<div className={styles.container}>
<main className={styles.main}>
<Count />
<IncreaseCount />
<DecreaseCount />
<ResetButton />
</main>
</div>
);
};
export default Home;
参考
zustand
zustand(Github Repository)
zustandを初めて使ってみた
軽量なグローバル状態管理ライブラリ「zustand」
React状態管理ライブラリ Zustandを使ってみた
Zustandの使い方