Atom
•
상태 단위
•
업데이트 가능하고 구독이 가능합니다
•
각각의 구독된 컴포넌트들은 새로운 Value에 따라 Re-Rendering이 이뤄집니다.
•
런타임 때 생성됩니다.
Atom을 생성하고자하면, 이런 식으로 사용해주면 됩니다.
atom()함수를 사용하시면 돼요.
const eomJunSikState = atom({
key: 'alive',
default: false,
});
// default : useState()에서 소괄호 안에 주는 default값이라고 생각해주세요.
// key : 필수한 유니크한 값. 두 개 이상의 atom이 key이름이 겹치면 안됩니다.
JavaScript
복사
이제 atom을 컴포넌트에서 읽고 쓰려고 한다면,
React에서 useState를 사용하듯이 useRecoilState라는 훅을 사용하시면 돼요.
const isEomAlive = () => {
const [eomState, setEomState] = useRecoilState(eomJunSikState);
return (
<button onClick=() => setEomState(!eomState)>
Click!!
</button>
<h1>
{eomState ? (그는 살아있어요!) : (모두 묵념해주세요..)}
</h1>
)
}
JavaScript
복사
버튼을 누른다면 State의 default값이 false
true를 오가겠죠?
그에 따라 h1태그의 내용도 변할겁니다.
Selector
•
순수 함수
◦
Atom들과 다른 Selector들이 input으로써 가능하도록 만들어주는 함수
◦
input값으로써 들어온 Upstream atoms나 Selectors가 업데이트가 되면, Selector 함수도 다시 평가됩니다(Re-evaluated).
•
컴포넌트들은 Atom때처럼 Selector를 구독할 수 있고, 그에 따라 Selector가 변화하면 리렌더링이 발생합니다.
Since selectors keep track of what components need them and what state they depend on, they make this functional approach very efficient.
From the point of view of components, selectors and atoms have the same interface and can therefore be substituted for one another.
저는 이 윗 두 문장이 Selector의 핵심 문장이라고 생각이 됩니다.
1.
selector는 컴포넌트들이 필요로 하는 state들을 계속 추적한다.
2.
컴포넌트의 관점에서는, selector와 atom은 같은 인터페이스를 지니고 있다.
아마 두 번째 문장은 무슨 말인가 싶을 수도 있을 것 같습니다.
인터페이스는 곧 원격 조종 규약같은 거죠.
그러니까, 구독하는 컴포넌트 입장에서는 atom가 selector는 같은 조종 방식을 가지고 있다라고 생각하시면 될 것 같아요.
제가 느끼기엔 마치 컴포넌트에서 하나의 리모컨으로 atom과 selector라는 두 개의 장치를 접근할 수 있으므로 두 가지는 서로 대체 가능하다라고 느껴집니다.
// 아래와 같은 atom이 있다고 해볼게요
const EnglishSpellState = atom({
key: 'EnglishSpellState',
default: 'A',
})
// selector는 selector()함수를 이용하면 됩니다.
const EnglishSpellLabelState = selector({
key: 'EnglishSpellLabelSizeState',
get: ({get}) => {
const spelling = get(EnglishSpellState);
return `This is ${spelling}`;
}
})
JavaScript
복사
get()함수 안에 key값을 넣는건 아닙니다
get property를 사용하면 atom과 selector의 value에 접근할 수 있습니다.
위에 제가 atom, selector는 같은 인터페이스로서 작동하기에 서로 대체 가능하다고 했었습니다
