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

ズースタンド?

https://github.com/pmndrs/zustand/raw/main/docs/bear.jpg
(Zustand公式ドキュメントより引用)

Zustandは複数のコンポーネント間での状態管理用のライブラリです。
useContext()などでは一つの状態が変わると、依存関係のある他のコンポーネントをまとめて再レンダリングしてしまい、パフォーマンスが低下することがあります。
その際に「Redux」や「Zustand」というライブラリが使われます。

Zustandは学習コストが低く、React初心者でも楽々導入できたのでその備忘録として紹介します。

使用しているフレームワーク・ライブラリ

  • Next.js 15.2.2 (App Router 使用
  • React 19.0.0
  • TypeScript ^5
  • Zustand 5.03

インストール

npm install zustand

使い方はこれだけ

①app直下にstoreフォルダを作成し、useStore.tsxを作成する

@/app/store/useStore.tsx
"use client";
import { create } from "zustand";

// Storeの型
interface StoreState {
  count: number;
  increment: () => void;
}

// Zustandのストアを作成
export const useStore = create<StoreState>((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}));

②あとはuseStateのように別コンポーネントで呼び出すだけ!

別のコンポーネント
"use client";
import {useStore} from "@/app/store/useStore"
const App = () => {
  const { count, increment } = useStore();
  //なんかの処理
  
  return (
    <div>
    //なんかの処理
       <p>{count}</p>
       <button onClick={increment}>1増やす</buttoon>
    </div>
  );
};

これだけなんです。

私もまだまだ初心者なので、何か改善点などがあればコメントお待ちしています。🙇

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?