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?

【React】状態管理ライブラリ「Zustand」の使い方

Posted at

Reactアプリに状態管理ツール「Zustand」について説明します。

完成イメージ

image.png

Zustand公式サイト

トップページ

公式ドキュメント

導入手順

1.パッケージツールでZustandをインストール

パッケージツールでZustandをインストールします。

npm install zustand

2.ストアの作成

src/store/useCounterStore.ts などのファイルを作成します。

src/store/useCounterStore.ts
import { create } from 'zustand';

type CounterState = {
  count: number;
  increase: () => void;
  decrease: () => void;
  reset: () => void;
};

// Zustandのstoreを作成
export const useCounterStore = create<CounterState>((set) => ({
  count: 0,
  increase: () => set((state) => ({ count: state.count + 1 })),
  decrease: () => set((state) => ({ count: state.count - 1 })),
  reset: () => set({ count: 0 }),
}));

3.コンポーネント開発

どのコンポーネントからでも、Hookとして呼び出して状態を参照・更新できます。

src/zustandComponents/Counter.tsx
import React from 'react';
import { useCounterStore } from '@/store/useCounterStore';
import { Button, Group } from '@chakra-ui/react';

export const Counter: React.FC = () => {
  const { count, increase, decrease, reset } = useCounterStore();
  return (
    <div style={{ textAlign: 'center' }}>
      <h2>Count: {count}</h2>
      <Group>
        <Button onClick={increase} alignSelf="flex-start" backgroundColor="blue.500"></Button>
        <Button onClick={decrease} alignSelf="flex-start" backgroundColor="green.500"></Button>
        <Button onClick={reset} alignSelf="flex-start" backgroundColor="gray.500">
          リセット
        </Button>
      </Group>
    </div>
  );
};

4.アプリに組み込む

ZustandはReact Contextを使わないため、特別なProviderを追加する必要はありません。

src/App.tsx に直接使えます。

src/App.tsx
import './App.css';
import { Counter } from '@/zuztandComponents/Counter';

function App() {
  return (
    <div>
      <h1>Zustand Example</h1>
      <Counter />
    </div>
  );
}

export default App;

5. (おまけ)永続化したい場合

Zustandpersistモジュールを使って永続化させることができます。

src/store/useCounterStore.ts
import { create } from 'zustand'
import { persist } from 'zustand/middleware'

type CounterState = {
  count: number
  increase: () => void
  decrease:()=>void;
  reset: () => void
}

export const useCounterStore = create<CounterState>()(
  persist(
    (set) => ({
      count: 0,
      increase: () => set((state) => ({ count: state.count + 1 })),
      decrease: () => set((state) => ({ count: state.count - 1 })),
      reset: () => set({ count: 0 }),
    }),
    {
      name: 'counter-storage', // localStorage key
    }
  )
)

まとめ

 やりたいこと   方法 
 グローバルステートを作る   create() でStoreを作成 
 ステートを使う   const { ... } = useStore() 
 ストレージ永続化   persistミドルウェアを使う 
 DevTools連携   devtoolsミドルウェアを追加 

サイト

tanstack-queryについて

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?