What is Recoil
- Recoil is a state management library for React
- React のための状態管理ライブラリ
Motivation
Recoilは、Reactツリーに直交するだけでなく、固有でアタッチされた有向グラフを定義します。状態の変化は、このグラフのルート(アトムと呼ばれます)から純粋関数(セレクターと呼ばれます)を経由してコンポーネントに流れます。
Core conceptes
Recoilを使用すると、アトム(共有状態)からセレクター(純粋関数)を経由してReactコンポーネントに流れるデータフローグラフを作成できます。アトムは、コンポーネントがサブスクライブできる状態の単位です。セレクターは、この状態を同期的または非同期的に変換します。
Official
- RecoilRoot
- Components that use recoil state need RecoilRoot to appear somewhere in the parent tree. A good place to put this is in your root component.
- atom
- An atom represents a piece of state. Atoms can be read from and written to from any component. Components that read the value of an atom are implicitly subscribed to that atom, so any atom updates will result in a re-render of all components subscribed to that atom.
- selector
- A selector represents a piece of derived state. Derived state is a transformation of state. You can think of derived state as the output of passing state to a pure function that modifies the given state in some way.
In my opinion
- RecoilRoot
- コンポーネントの Root に RecoilRoot を宣言する必要がある。このコンポーネントの子コンポーネントで state を扱うことができる。useContext と同様な感じ。
- atom
- 状態の最小単位を定義する関数。React の useState と似たように使用する。純粋な値を読み込んだり書き込んだりする。value, setFunction のような感じ。atom に subscribe されているコンポーネントは atom の値が書き換わると re-render される。subscribe されていないコンポーネントは re-render されない。(context は re-render されたコンポーネントの子コンポーネントは re-render されてしまう)
- selector
- atom に依存して、atom の値に何かしらの処理をした値を返却したい時に利用する。例えば、atom で管理している order list を受け取って、ある値でフィルタリングしたい場合に selector を使用する。
How to use
RecoilRoot
function App() {
return (
<RecoilRoot>
<CharacterCounter />
</RecoilRoot>
);
}
atom
const todoListState = atom({
key: 'todoListState',
default: [],
});
const todoList = useRecoilValue(todoListState);
selector
const filteredTodoListState = selector({
key: 'filteredTodoListState',
get: ({get}) => {
const filter = get(todoListFilterState);
const list = get(todoListState);
switch (filter) {
case 'Show Completed':
return list.filter((item) => item.isComplete);
case 'Show Uncompleted':
return list.filter((item) => !item.isComplete);
default:
return list;
}
},
});
const todoList = useRecoilValue(filteredTodoListState);
Asynchronous Data Queries
https://recoiljs.org/docs/guides/asynchronous-data-queries