Recoil基礎
Recoil基礎
Section titled “Recoil基礎”Recoilは、Facebookが開発したアトミックな状態管理ライブラリです。
インストール
Section titled “インストール”npm install recoilAtomの定義
Section titled “Atomの定義”import { atom } from 'recoil';
export const countState = atom({ key: 'countState', default: 0,});Selectorの定義
Section titled “Selectorの定義”import { selector } from 'recoil';import { countState } from './atoms';
export const doubleCountState = selector({ key: 'doubleCountState', get: ({ get }) => { const count = get(countState); return count * 2; },});コンポーネントでの使用
Section titled “コンポーネントでの使用”import { useRecoilState, useRecoilValue } from 'recoil';import { countState, doubleCountState } from './atoms';
function Counter() { const [count, setCount] = useRecoilState(countState); const doubleCount = useRecoilValue(doubleCountState);
return ( <div> <p>Count: {count}</p> <p>Double: {doubleCount}</p> <button onClick={() => setCount(count + 1)}>+</button> </div> );}