16
2

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学習ログ No.15

Posted at

React状態管理「Recoil」学習メモ

1. Recoilとは

  • React用状態管理ライブラリ

2. 環境構築

  • インストール:
    npm i recoil
    # または
    yarn add recoil
    
  • 設定:
    • アプリケーションのルート(index.jsApp.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>;
    }
    
16
2
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
16
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?