๐ React๋ฅผ ์ํ ์ํ๊ด๋ฆฌ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
์ํ(state)์ ์ผ๋ถ๋ฅผ ๋ํ๋
์ด๋ค ์ปดํฌ๋ํธ์์๋ ์ฝ๊ณ ์ธ ์ ์์
atom ๊ฐ์ ์ฝ๋ ์ปดํฌ๋ํธ๋ค์ ์๋ฌต์ ์ผ๋ก atom์ ๊ตฌ๋ ํ๋ค.
- ๋ณํ๋ฅผ ๊ฐ์งํ๋ฉด, atom์ ๊ตฌ๋ ํ๋ ๋ชจ๋ ์ปดํฌ๋ํธ๋ค์ด rerendering
const textState = atom<T>({
key: 'unique key',
default: ''
})
function TextInput() {
// ~ useRecoilValue(atom key value | selector)
const [text, setText] = useRecoilValue(unique_key);
const onChange = (e) => setText(e.target.value);
return ({
<div>
<input type="text" value={text} onChange={onChange}/>
Echo: {text}
</div>
});
}
ํ์๋ ์ํ(derived state)์ ์ผ๋ถ๋ฅผ ๋ํ๋
ํ์๋ ์ํ๋ ์ํ์ ๋ณํ
์ํ์ ๋ณํ์ ๋ฐ๋ผ ์ํ๋ ํฌ๋งท์ ์ค์ ํ์ฌ ๊ฐ์ ธ์ฌ ์ ์์
์ผ๋ถ๋ง ์ฐ๊ธฐ ๊ฐ๋ฅํ ์ํ(get๊ณผ set ์์ฑ์ ๋๋ค ๊ฐ์ง๊ณ ์์)
const charCountState = selector({
key: 'charCountState',
get: ({get}) => {
// ~ get(atom key value)
const text = get(unique_key); // ํด๋น recoil value๋ฅผ ๊ฐ์ ธ์ด
return text.length;
},
});
function CharCounter() {
const count = useRecoilValue(charCountState);
return <>Char count: {count} </>
}
atom์ ๊ฐ์ ๊ฐ์ ธ์ค๋ hook(getter)
const todoListState = atom({
key: 'todoListState',
default: []
});
function TodoList() {
const todoList = useRecoilValue(todoListState);
return (<> ... </>)
}
atom์ ๊ฐ ์ ๋ฐ์ดํธ(setter)
๋ฆฌ์คํธ์ผ๊ฒฝ์ฐ updater ํ์์ ์ฌ์ฉํ๋์ ์ ์ ์
const setTodoList = useSetRecoilState(todoListState);
setTodoList((oldTodoList) => [...oldTodoList, { newListItem } ]);