recoil 시작하기 참고
https://recoiljs.org/ko/docs/introduction/getting-started
Atom은 상태(state)의 일부를 나타낸다.
Atoms는 어떤 컴포넌트에서나 읽고 쓸 수 있다.
atom의 값을 읽는 컴포넌트들은 암묵적으로 atom을 구독한다.
그래서 atom에 어떤 변화가 있으면 그 atom을 구독하는 모든 컴포넌트들이 재렌더링 되는 결과가 발생할 것이다.
// textState
const textState = atom({
key: 'textState', // unique ID (with respect to other atoms/selectors)
default: '', // default value
});
key는 고유값으로 설정
default는 초기값 이라고 보면 된다.
import { textState } from '../state';
import { useRecoilState } from 'recoil';
cosnt TextInput = () => {
const [text, setText] = useRecoilState(textState);
const onChange = (e) => {
setText(e.target.value);
};
return (
<div>
<input type="text" value={text} onChange={onChange} />
<br />
Echo: {text}
</div>
);
}
useRecoilState
를 이용하여 state를 전역으로 받아올 수 있고 변경도 할 수 있다.
Selector는 파생된 상태(derived state) 의 일부를 나타낸다.
파생된 상태는 상태의 변화다.
파생된 상태를 어떤 방법으로든 주어진 상태를 수정하는 순수 함수에 전달된 상태의 결과물로 생각할 수 있다.
const charCountState = selector({
key: 'charCountState',
get: ({get}) => {
const text = get(textState);
return text.length;
},
});