React状態管理「Recoil」学習メモ
1. Recoilとは
- React用状態管理ライブラリ
2. 環境構築
-
インストール:
npm i recoil # または yarn add recoil -
設定:
- アプリケーションのルート(
index.jsやApp.jsなど)を<RecoilRoot>で囲む
import { RecoilRoot } from 'recoil'; ReactDOM.render( <RecoilRoot> <App /> </RecoilRoot>, document.getElementById('root') ); - アプリケーションのルート(
3. Atom (状態の定義)
-
atomは状態の単位 -
useStateのstateに似ているが、どこからでも参照・更新可能 -
定義方法 (
src/atoms/someState.jsなど):import { atom } from 'recoil'; export const textState = atom({ key: 'textState', // 必須: プロジェクト内でユニークなID default: '', // 必須: 初期値 }); export const countState = atom({ key: 'countState', default: 0, });
4. コンポーネントでの使用 (Hooks)
4-1. useRecoilState
-
useStateとほぼ同じ感覚で使える - [値, セッター関数] のタプルを返す
-
使用例:
import { useRecoilState } from 'recoil'; import { textState } from './atoms/someState'; function TextInput() { const [text, setText] = useRecoilState(textState); const onChange = (event) => { setText(event.target.value); }; return ( <div> <input type="text" value={text} onChange={onChange} /> <p>Echo: {text}</p> </div> ); }
4-2. useRecoilValue
- 値の読み取り専用。
- コンポーネントが値のみに依存する場合に使う。(セッター関数は不要な場合)
-
使用例:
import { useRecoilValue } from 'recoil'; import { textState } from './atoms/someState'; function DisplayText() { const text = useRecoilValue(textState); return <p>Current text: {text}</p>; }
4-3. useSetRecoilState
- セッター関数のみを取得
- 値の更新のみを行い、その値の変更による再レンダリングを
トリガーしたくない場合に使用(例: ボタンクリックで値をリセットするだけ、など) -
使用例:
import { useSetRecoilState } from 'recoil'; import { countState } from './atoms/someState'; function ResetButton() { const setCount = useSetRecoilState(countState); return <button onClick={() => setCount(0)}>Reset Count</button>; }
5. Selector (派生データ)
-
atomや他のselectorから計算される派生データ -
atomの値が変更されると、selectorの値も自動で再計算される -
定義方法:
import { selector } from 'recoil'; import { textState } from './atoms/someState'; export const charCountState = selector({ key: 'charCountState', // 必須: ユニークID get: ({ get }) => { // get関数を使って他のatom/selectorの値を取得 const text = get(textState); return text.length; }, }); -
使用方法 (読み取り専用):
-
atomと同様にuseRecoilValueを使う
import { useRecoilValue } from 'recoil'; import { charCountState } from './atoms/someState'; function CharacterCount() { // selectorの値を読み取る const count = useRecoilValue(charCountState); return <p>Character Count: {count}</p>; } -