0
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.

【React状態管理5】Recoil

Posted at

概要

Reactの状態管理の1つである、Recoilについて学んだことをメモします。

学習内容

Recoilとは

Meta製の、Atomsベースの状態管理ライブラリ。
Selectorsを使うことで、複数のatomを合わせた状態を利用することもできる。

Recoilの構成図
^1

特長

  • 比較的容易に利用できる
  • Atomベースのため、各データの状態を個別に管理できる

導入方法

インストール方法

$ npm install recoil

or

$ yarn add recoil

設定方法

  1. 最上位の関数をRecoilRootでラップする
    import React from 'react';
    import {
        RecoilRoot,
        atom,
        selector,
        useRecoilState,
        useRecoilValue,
    } from 'recoil';
    
    function App() {
        return (
            <RecoilRoot>
                <CharacterCounter />
            </RecoilRoot>
        );
    }
    
  2. atom()メソッドで状態のオブジェクトを追加する
    key:atomのキー(アプリ内でユニークである必要がある)
    default:状態の初期値
    const textState = atom({
        key: 'textState', // unique ID (with respect to other atoms/selectors)
        default: '', // default value (aka initial value)
    });    
    
  3. useRecoilStateで状態を取得、更新する
    useRecoilStateの使い方は、基本的にuseStateと同じ。下記では、文字入力によりtextStateの状態を更新している。
    function CharacterCounter() {
        return (
            <div>
                <TextInput />
                <CharacterCount />
            </div>
        );
    }
    
    function TextInput() {
        const [text, setText] = useRecoilState(textState);
    
        const onChange = (event) => {
            setText(event.target.value);
        };
    
        return (
            <div>
                <input type="text" value={text} onChange={onChange} />
                <br />
                Echo: {text}
            </div>
        );
    }
    
  4. selectorであるatomの状態を変換し、useRecoilValueで取得する
    下記では、文字データtextStateselectorで文字データの長さcharCountStateに変換し、useRecoilValueで取得している。
    const charCountState = selector({
        key: 'charCountState', // unique ID (with respect to other atoms/selectors)
        get: ({get}) => {
            const text = get(textState);
    
            return text.length;
        },
    });
    
    function CharacterCount() {
        const count = useRecoilValue(charCountState);
    
        return <>Character Count: {count}</>;
    }
    

selectorを用いる利点

  • シンプルに記述できる
  • パフォーマンスが向上する
    レンダリングを行う場所を更新箇所のみにできる

参考

IT Kingdom
Recoil公式ページ
ATOMOS
GitHubリポジトリ

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