Recoil이란 페이스북에서 만든 리액트 상태 관리 라이브러리입니다.
Recoil의 가장 큰 장점은 다른 상태관리 라이브러리에 비해 배우기 쉽다는 것입니다. API 구조가 단순하고 이미 hook을 사용해본 경험이 있다면 금방 적응할 수 있습니다.
# react(next) app 설치 후 recoil 설치
npx create-react-app my-app
# npx create-next-app my-app
npm install recoil
# yarn add recoil
// App.tsx
import React from 'react';
import {
RecoilRoot,
atom,
selector,
useRecoilState,
useRecoilValue,
} from 'recoil';
function App() {
return (
<RecoilRoot>
<CharacterCounter />
</RecoilRoot>
);
}
atom은 React의 useState와 비슷합니다. 컴포넌트는 atom을 구독하고 atom 값이 변경되면 그것을 구독하고 있던 컴포넌트들이 렌더링 됩니다. atom을 생성하기 위해는 다음과 같이 정의 합니다.
// src/atoms/textState.ts
import {atom} from 'recoil';
export const textState({
key:"textState", // unique ID (with respect to other atoms/selectors)
default: "", // default value (aka initial value)
});
import {useRecoilState} = from "recoil"
import {textState} from "../atom/textState"
function TextInput() {
const [text, setText] = useRecoilState(textState)
return (
<div>
{text}
</div>
)
}
select는 파생된 상태의 일부입니다. 바로 예제를 통해 알아봅시다.
우리가 정의한 textState 값을 받아와서 textState의 문자열 길이를 반환합니다.
const charCountState = selector({
key: 'charCountState', // unique ID (with respect to other atoms/selectors)
get: ({get}) => {
const text = get(textState);
return text.length;
},
});
function CharacterCount() {
const count = useRecoilValue(charCountState);
return <>Character Count: {count}</>;
}
atom과 select를 이용하여 몇가지 코드만 작성하면 전역에서 상태관리할 수 있다는게 정말 편리했습니다. 기존의 React Hooks들과 사용법도 크게 다르지 않아 쉽게 사용할 수 있는 것 같습니다.