Skip to content

Recoil基礎

Recoilは、Facebookが開発したアトミックな状態管理ライブラリです。

Terminal window
npm install recoil
import { atom } from 'recoil';
export const countState = atom({
key: 'countState',
default: 0,
});
import { selector } from 'recoil';
import { countState } from './atoms';
export const doubleCountState = selector({
key: 'doubleCountState',
get: ({ get }) => {
const count = get(countState);
return count * 2;
},
});
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>
);
}