TIL(Today I Learned)/스파르타 내배캠
[TIL] 23/12/21 전역관리 혁신이댜~ Recoil
개발자먼지
2023. 12. 21. 21:11
반응형
재밌었다~
남상림 튜터님 예뻐여..
TIL
Redux 대신 Recoil 을 써보자~
사실 tutorial 그대로라 다시 옮겨 적을 필요는 없지만.. ㄷㄷㄷ
복습차원으로..
recoil 패키지 설치
yarn add recoil
recoilRoot
redux의 provider 처럼 App.jsx에 전역으로 사용하려는 범위에 감싸 놓기
import React from 'react';
import {
RecoilRoot,
atom,
selector,
useRecoilState,
useRecoilValue,
} from 'recoil';
function App() {
return (
<RecoilRoot>
<CharacterCounter />
</RecoilRoot>
);
}
Atom
전역으로 사용하려는 state 변수를 atom을 사용해서 끄적여 준다. key값은 고유값, 보통 변수명과 동일하게 사용.
이 atom을 구독하면 구독하는 모든 컴포넌트가 재 렌더링된다.
const textState = atom({
key: 'textState', // unique ID (with respect to other atoms/selectors)
default: '', // default value (aka initial value)
});
useRecoilState
useState와 매우 동일한 사용법으로 atom으로 만든 state를 가져다 쓴다.
set만 하는애useSetRecoilState(), 읽기만하는 애(useRecoilValue()) 훅도 따로있다.
const [text, setText] = useRecoilState(textState);
selector
위에서 선언한놈을 get 해다가 고쳐서 쓰는 놈이다!
원래의 atom 값을 이용하여 조작한 다음 새로운 값을 반환하는 순수함수이다.
const charCountState = selector({
key: 'charCountState', // unique ID (with respect to other atoms/selectors)
get: ({get}) => {
const text = get(textState);
return text.length;
},
});
나중에 좀더 ~ 히히
반응형