[React] Recoil

Goniยท2022๋…„ 6์›” 8์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
4/4

Recoil์ด๋ž€?

๐Ÿ‘‰ React๋ฅผ ์œ„ํ•œ ์ƒํƒœ๊ด€๋ฆฌ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ



Atom

์ƒํƒœ(state)์˜ ์ผ๋ถ€๋ฅผ ๋‚˜ํƒ€๋ƒ„
์–ด๋–ค ์ปดํฌ๋„ŒํŠธ์—์„œ๋‚˜ ์ฝ๊ณ  ์“ธ ์ˆ˜ ์žˆ์Œ
atom ๊ฐ’์„ ์ฝ๋Š” ์ปดํฌ๋„ŒํŠธ๋“ค์€ ์•”๋ฌต์ ์œผ๋กœ atom์„ ๊ตฌ๋…ํ•œ๋‹ค.
- ๋ณ€ํ™”๋ฅผ ๊ฐ์ง€ํ•˜๋ฉด, atom์„ ๊ตฌ๋…ํ•˜๋Š” ๋ชจ๋“  ์ปดํฌ๋„ŒํŠธ๋“ค์ด rerendering

atom ์„ ์–ธ

const textState = atom<T>({
	key: 'unique key',
	default: ''
})

atom ์‚ฌ์šฉ

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>
	});
}



Selector

ํŒŒ์ƒ๋œ ์ƒํƒœ(derived state)์˜ ์ผ๋ถ€๋ฅผ ๋‚˜ํƒ€๋ƒ„
ํŒŒ์ƒ๋œ ์ƒํƒœ๋Š” ์ƒํƒœ์˜ ๋ณ€ํ™”
์ƒํƒœ์˜ ๋ณ€ํ™”์— ๋”ฐ๋ผ ์›ํ•˜๋Š” ํฌ๋งท์„ ์„ค์ •ํ•˜์—ฌ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์Œ
์ผ๋ถ€๋งŒ ์“ฐ๊ธฐ ๊ฐ€๋Šฅํ•œ ์ƒํƒœ(get๊ณผ set ์†์„ฑ์„ ๋‘˜๋‹ค ๊ฐ€์ง€๊ณ  ์žˆ์Œ)

selector ์„ ์–ธ ๋ฐ ํ™œ์šฉ

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} </>  
}



Hooks

useRecoilValue(key)

atom์˜ ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๋Š” hook(getter)

    const todoListState = atom({
    	key: 'todoListState',
    	default: []
    });
    
    function TodoList() {
    	const todoList = useRecoilValue(todoListState);
    
    	return (<> ... </>)
    }

useSetRecoilState(key)

atom์˜ ๊ฐ’ ์—…๋ฐ์ดํŠธ(setter)
๋ฆฌ์ŠคํŠธ์ผ๊ฒฝ์šฐ updater ํ˜•์‹์„ ์‚ฌ์šฉํ•˜๋Š”์ ์— ์œ ์˜

const setTodoList = useSetRecoilState(todoListState);

setTodoList((oldTodoList) => [...oldTodoList, { newListItem } ]);

0๊ฐœ์˜ ๋Œ“๊ธ€