전역 상태관리 라이브러리 중 하나
import { atom } from 'recoil';
const counterState = atom({
key: 'counterState',
default: 0
});
import { selector } from 'recoil';
...
const fontSizeLabelState = selector({
key: 'fontSizeLabelState',
get: ({get}) => {
const fontSize = get(fontSizeState);
const unit = 'px';
return `${fontSize}${unit}`;
},
});
import { useRecoilState, useRecoilValue } from 'recoil';
function FontButton() {
const [fontSize, setFontSize] = useRecoilState(fontSizeState);
const fontSizeLabel = useRecoilValue(fontSizeLabelState);
return (
<>
<div>Current font size: ${fontSizeLabel}</div>
<button onClick={setFontSize(fontSize + 1)} style={{fontSize}}>
Click to Enlarge
</button>
</>
);
}
useRecoilState()
: useState()와 유사useRecoilValue()
: 전역상태의 state 상태값만을 참조useSetRecoilState()
: 전역상태의 setter 함수만을 활용useResetRecoilState()
: default(초기값)으로 Reset 하기 위해 사용hasValue → value
hasError → Error
loading → Promise