14
11

More than 1 year has passed since last update.

[JavaScript] Reactの状態管理にはZustandが決定解になるような気がする

Last updated at Posted at 2022-09-30

useStateと同じ感覚で、グローバルのstoreをかけるので、これが最も使いやすいstore管理なのではないかなと思います。

今まで状態管理で、ReduxとかMobxとか、あれやこれや悩んでいたことが嘘のように一掃される感。

俺はこれを待ってたんだ感がします。すごいライブラリ!

zustand - npm
https://www.npmjs.com/package/zustand

pmndrs/zustand: 🐻 Bear necessities for state management in React
https://github.com/pmndrs/zustand

Code

App.js
import { useStore } from "./store";
import "./styles.css";

export default function App() {
  const countDefault = 1;
  const { count = countDefault, setCount } = useStore();

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <h2>count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increase</button>
      <button onClick={() => setCount(count - 1)}>Decrease</button>
      <button onClick={() => setCount(countDefault)}>Reset</button>
    </div>
  );
}
store.js
import create from "zustand";

export const useStore = create((set) => ({
  count: undefined,
  setCount: (value) =>
    set((state) => {
      return { count: value };
    })
}));

image.png

codesandbox

記事でコードのせた単純なstoreのもの

下記の画像のような多数のコンポーネント間のstoreの連携

image.png

参考

React状態管理ライブラリ Zustandを使ってみた | DevelopersIO
https://dev.classmethod.jp/articles/zustand/

Reactで状態管理 初心者でも簡単Zustandの設定方法 | アールエフェクト
https://reffect.co.jp/react/zustand

ZustandとValtioの比較
https://zenn.dev/dai_shi/articles/f848fb75650753

Zustand: React向け軽量ステート管理ライブラリ - Qiita
https://qiita.com/daishi/items/deb20d951f532b86f029

なんで、多くの紹介サイトが、store側で、increaseとかdecreaseとか定義しているのかわからないけど
store側では、setCount を定義したらいいのに。

14
11
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
14
11