npm install recoil
혹은 yarn add recoil
recoil 상태를 사용하는 컴포넌트는 부모 트리 어딘가에 RecoilRoot
가 필요하다. 루트 컴포넌트가 RecoilRoot
를 넣기에 가장 좋다.
import React from 'react';
import {
RecoilRoot,
atom,
selector,
useRecoilState,
useRecoilValue,
} from 'recoil';
function App() {
return (
<RecoilRoot>
<CharacterCounter />
</RecoilRoot>
);
}
// Atom 작성 예시
const textState = atom({
key:'textState',
default:'',
});
// 컴포넌트에서 Atom 읽고 쓰기. 여기선 useRecoilState 사용
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 에시
const charCountState = selector({
key: 'charCountState', // unique ID (with respect to other atoms/selectors)
get: ({get}) => {
const text = get(textState);
return text.length;
},
});
위의 코드는 get
프로퍼티를 이용해 atom
의 textState
을 가공하여 text의 길이를 반환한다.
// 컴포넌트에서의 selector 사용 예시
function CharacterCount() {
const count = useRecoilValue(charCountState);
return <>Character Count: {count}</>;
}
references : https://recoiljs.org/docs/guides/