JavaScript/상태관리
Recoil의 기본 개념 이모저모
유니엘.
2022. 8. 17. 23:48
RecoilRoot
recoil 상태를 사용하는 컴포넌트는 부모 트리 어딘가에 나타나는 RecoilRoot가 필요하다. 루트 컴포넌트가 RecoilRoot를 넣기에 가장 좋은 장소이다.
import React from 'react';
import {
RecoilRoot,
atom,
selector,
useRecoilState,
useRecoilValue,
} from 'recoil';
function App() {
return (
<RecoilRoot>
<컴포넌트 />
</RecoilRoot>
);
}
Atom
아톰은 상태(state)의 일부를 나타낸다. Atoms는 어느 컴포넌트에서나 읽고 쓸 수 있다. 아톰의 값을 읽는 컴포넌트들은 암묵적으로 atom을 구독한다. 그래서 atom에 어떤 변화가 있으면 그 atom을 구독하는 모든 컴포넌트들이 재 랜더링 되는 결과가 발생한다.
const textState = atom({
key: 'textState', // unique ID (with respect to other atoms/selectors)
default: '', // default value (aka initial value)
});
컴포넌트가 atom을 읽고 쓰게 하기 위해서는 useRecoilState()를 사용한다.
function CharacterCounter() {
return (
<div>
<TextInput />
<CharacterCount />
</div>
);
}
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
selector는 derived state(파생된 상태)의 일부를 나타낸다. 파생된 상태란 상태의 변화를 의미하는데, 어떤 방법으로든 주어진 상태를 수정하는 순수 함수에 전달된 상태의 결과물로 생각할 수 있다.
const charCountState = selector({
key: 'charCountState', // unique ID (with respect to other atoms/selectors)
get: ({get}) => {
const text = get(textState);
return text.length;
},
});
useRecoilValue를 사용하여 값을 읽을 수 있다.
function CharacterCount() {
const count = useRecoilValue(charCountState);
return <>Character Count: {count}</>;
}