Recoil은 React를 위한 상태관리 라이브러리이다.
🤔 Recoil은 context-api의 단점인 provider로 감싸진 부분의 업데이트가 되지 않은 state에도 리렌더가 일어나는 점을 보완해서, 업데이트된 state 부분만 리렌더를 해준다. useState와 사용법이 동일하여 매우 손쉽게 사용할 수 있다.
Recoil 패키지는 npm에 존재한다.
npm install recoil
을 입력합니다.yarn add recoil
을 입력합니다.컴포넌트들이 전역상태를 사용하기 위해선 RecoilRoot 컴포넌트를 부모 컴포넌트로 가져야한다.
recoil 상태를 사용하는 컴포넌트는 부모 트리 어딘가에 나타나는 RecoilRoot 가 필요하다. 루트 컴포넌트가 RecoilRoot를 넣기에 가장 좋은 장소다.
import "../styles/globals.css";
import type { AppProps } from "next/app";
import Layout from "../src/layout/Layout";
import {
RecoilRoot,
atom,
selector,
useRecoilState,
useRecoilValue,
} from "recoil";
export default function App({ Component, pageProps }: AppProps) {
return (
<RecoilRoot>
<Layout>
<Component {...pageProps} />
</Layout>
</RecoilRoot>
);
}
Atom은 상태(state)의 일부를 나타낸다. Atoms는 어떤 컴포넌트에서나 읽고 쓸 수 있다. atom의 값을 읽는 컴포넌트들은 암묵적으로 atom을 구독한다. 그래서 atom에 어떤 변화가 있으면 그 atom을 구독하는 모든 컴포넌트들이 리렌더링 되는 결과가 발생할 것이다.
import { atom } from "recoil";
export const currentLangState = atom({
key: "currentLangState",
default: "English",
});
컴포넌트가 atom을 읽고 쓰게 하기 위해서는 useRecoilState()를 아래와 같이 사용하면 된다.
import { currentLangState } from "../../../recoil/language";
import { useRecoilState } from "recoil";
const [currentLang, setCurrentLang] = useRecoilState(currentLangState);
setCurrentLang(languages[i].lang);
<Lang.CurrentLanguage>{currentLang}</Lang.CurrentLanguage>
정의와 사용방법 모두가 useState와 동일한 모습이다.
🙋🏻♂️ 부모컴포넌트에서 atom을 읽어와 자식 컴포넌트로 props도 가능하다!