0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

zustandを使ってみたい

Posted at

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の使い方

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?