Recoil
은 전역 상태 관리 라이브러리이다.
기본적인 개념은, atom
이라는 상태 단위를 구독하거나 업데이트할 수 있고,
만약 atom
이 업데이트되면 이를 구독하고 있던 컴포넌트들이 새로 렌더링이 된다.
yarn add recoil
// App.tsx
import { RecoilRoot } from 'recoil';
const App = () => {
return(
<RecoilRoot>
//나머지 페이지들은 여기 넣어주기
</RecoilRoot>
)
}
// src/atoms/userState.ts
import { atom } from "recoil";
export const userState = atom({
key: "userState", // unique ID (with respect to other atoms/selectors)
default: "", // 자료형 따라 초기값을 다르게 설정해주자
});
import { useRecoilState } from 'recoil';
const [userState, setUserState] = useRecoilState(userState);
사용할 때는 다음과 같이, useState
처럼 사용하면 된다.