概要
Reactの状態管理の1つである、Recoil
について学んだことをメモします。
学習内容
Recoilとは
Meta製の、Atomsベースの状態管理ライブラリ。
Selectorsを使うことで、複数のatomを合わせた状態を利用することもできる。
特長
- 比較的容易に利用できる
- Atomベースのため、各データの状態を個別に管理できる
導入方法
インストール方法
$ npm install recoil
or
$ yarn add recoil
設定方法
- 最上位の関数を
RecoilRoot
でラップするimport React from 'react'; import { RecoilRoot, atom, selector, useRecoilState, useRecoilValue, } from 'recoil'; function App() { return ( <RecoilRoot> <CharacterCounter /> </RecoilRoot> ); }
-
atom()
メソッドで状態のオブジェクトを追加する
key
:atomのキー(アプリ内でユニークである必要がある)
default
:状態の初期値const textState = atom({ key: 'textState', // unique ID (with respect to other atoms/selectors) default: '', // default value (aka initial value) });
-
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> ); }
-
selector
であるatomの状態を変換し、useRecoilValue
で取得する
下記では、文字データtextState
をselector
で文字データの長さ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
を用いる利点
- シンプルに記述できる
- パフォーマンスが向上する
レンダリングを行う場所を更新箇所のみにできる