pmndrs/jotai: 👻 Primitive and flexible state management for React
Jotai, primitive and flexible state management for React
jotai は useState 的にグローバルに状態を管理する React のライブラリです。Redux 等の他のライブラリよりも小さくまとまっていて、React 組み込みのコンテキストよりも少ないコードで適切なレンダリング制御をしてくれます。
使い方の例は次です。
import React from "react";
import { Provider as JotaiProvider, atom, useAtom } from "jotai";
// ベースとなる宣言。この "hello"を atom を介して色々な場所で扱えます。
const textAtom = atom("hello");
const Input = () => {
// 基本の使い方です。初期値に宣言済みの atom を渡す useState な感じで使えます。
// 宣言済みの atom を渡す必要があるので何か間違えた時はすぐ気づけます
const [ text, setText ] = useAtom(textAtom);
return <input value={text} onChange={(e) => setText(e.target.value)} />;
};
// atom の中で別の atom を参照することもできます。
const textLenAtom = atom((get) => get(textAtom).length);
const CharCount = () => {
const [ len ] = useAtom(textLenAtom);
return <div>Atom Relay Length: {len}</div>;
};
// useAtom から読み込んだ値を素の JavaScript の時同様に扱えもします
const CharCountWithoutAtomRelay = () => {
const [ text ] = useAtom(textAtom);
return <div>No Atom Relay Length: {text.length}</div>;
};
// コンテキスト的に jotai のプロバイダーでくくった範囲で useAtom が使えます
const App = () => (
<JotaiProvider>
<Input />
<CharCount />
<CharCountWithoutAtomRelay />
</JotaiProvider>
);
export default App;
これぐらいならば特別覚えることも少なく React の性能を活かしつつ簡単にグローバルな状態管理ができます。
これをさらに便利にするための色々が
Jotai, primitive and flexible state management for React
に記述されています。Utils と Devtools だけでも流し読みしておくと jotai を使って何かしたい時、大体 jotai が既にそれを用意していることを知っておけます。