3
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?

More than 1 year has passed since last update.

はじめに

最近、状態管理ライブラリの下記記事をみました。
Redux,Recoilが有名でしたが、ZustandがReduxを追い抜く勢いなんですね。
普段開発ではjotaiを利用しているのですが、時代に追いつくためにもZustandを触っていこうと思います。

余談ですが、Recoilのversionは0.7.7のようですね。
https://github.com/facebookexperimental/Recoil/releases/tag/0.7.7

image.png

Zustandって何??

状態管理ライブラリです。最小限の設定で直感的な状態管理を行いたい場合、または関数型プログラミングのアプローチを好む場合に適してます。
スクリーンショット 2024-01-04 21.18.12.png

Hands-on

成果物です。
zustand.gif

ソースコード

ディレクトリ構成
~/develop/react/react_zustand$ tree src
src
├── App.tsx
├── index.tsx
├── logo.svg
└── store.ts

1 directory, 4 files
src/App.tsx
import React from 'react';
import { useCounterStore } from './store';

const App: React.FC = () => {
  const { count, increment, decrement } = useCounterStore();

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
};

export default App;
src/store.ts
import create from 'zustand';

interface CounterState {
  count: number;
  increment: () => void;
  decrement: () => void;
}

export const useCounterStore = create<CounterState>((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
}));

stateがオブジェクト型なのがいいですね。
Java出身のエンジニアとしては馴染みのある実装です。
また、オブジェクトの中に変数や振る舞いが集約されているのも気持ちいですね!!

まとめ

変数や振る舞いがオブジェクト型で定義されているので、すごい管理しやすい。

3
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
3
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?