[React] Recoil 기본 사용법 정리
포스트
취소

[React] Recoil 기본 사용법 정리

Recoil이란?

Recoil은 React에서 전역 상태를 관리하기 위한 라이브러리입니다.

컴포넌트 여러 곳에서 같은 상태를 읽거나 수정해야 할 때 props를 계속 내려보내지 않고 상태를 공유할 수 있게 도와줍니다.

Recoil의 핵심 개념은 atomselector입니다.


설치하기

1
npm install recoil

또는 yarn을 사용한다면 다음 명령어로 설치할 수 있습니다.

1
yarn add recoil

RecoilRoot 설정하기

Recoil 상태를 사용하려면 앱 최상단을 RecoilRoot로 감싸야 합니다.

1
2
3
4
5
6
7
8
9
10
import React from "react";
import ReactDOM from "react-dom/client";
import { RecoilRoot } from "recoil";
import App from "./App";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <RecoilRoot>
    <App />
  </RecoilRoot>,
);

RecoilRoot 아래에 있는 컴포넌트에서 atom과 selector를 사용할 수 있습니다.


atom 만들기

atom은 Recoil에서 상태를 저장하는 가장 작은 단위입니다.

1
2
3
4
5
6
import { atom } from "recoil";

export const countAtom = atom<number>({
  key: "countAtom",
  default: 0,
});

key는 atom을 구분하는 고유한 이름입니다.

default는 초기값입니다.


useRecoilState

useRecoilState는 React의 useState와 비슷하게 상태 값과 setter 함수를 함께 반환합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { useRecoilState } from "recoil";
import { countAtom } from "./atoms";

const Counter = () => {
  const [count, setCount] = useRecoilState(countAtom);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount((prev) => prev + 1)}>증가</button>
    </div>
  );
};

export default Counter;

상태를 읽고 수정해야 하는 컴포넌트에서 사용하면 됩니다.


useRecoilValue

상태를 읽기만 한다면 useRecoilValue를 사용할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
import { useRecoilValue } from "recoil";
import { countAtom } from "./atoms";

const CountText = () => {
  const count = useRecoilValue(countAtom);

  return <p>현재 값: {count}</p>;
};

export default CountText;

setter가 필요 없을 때는 useRecoilValue를 쓰면 의도가 더 명확해집니다.


useSetRecoilState

상태를 변경만 하고 읽을 필요가 없다면 useSetRecoilState를 사용할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
import { useSetRecoilState } from "recoil";
import { countAtom } from "./atoms";

const ResetButton = () => {
  const setCount = useSetRecoilState(countAtom);

  return <button onClick={() => setCount(0)}>초기화</button>;
};

export default ResetButton;

상태를 읽지 않기 때문에 해당 값이 바뀌어도 불필요한 렌더링을 줄일 수 있습니다.


selector란?

selector는 atom 값을 기반으로 계산된 값을 만들 때 사용합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { atom, selector } from "recoil";

export const priceAtom = atom<number>({
  key: "priceAtom",
  default: 10000,
});

export const quantityAtom = atom<number>({
  key: "quantityAtom",
  default: 2,
});

export const totalPriceSelector = selector<number>({
  key: "totalPriceSelector",
  get: ({ get }) => {
    const price = get(priceAtom);
    const quantity = get(quantityAtom);

    return price * quantity;
  },
});

사용하는 쪽에서는 atom처럼 읽을 수 있습니다.

1
const totalPrice = useRecoilValue(totalPriceSelector);

마무리

Recoil은 atom을 통해 전역 상태를 만들고, Recoil 훅으로 값을 읽거나 수정합니다.

useRecoilState는 읽기와 쓰기, useRecoilValue는 읽기, useSetRecoilState는 쓰기에 사용하면 됩니다.

계산된 값이 필요하다면 selector를 사용하면 상태에서 파생된 값을 깔끔하게 관리할 수 있습니다.

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.

[React] Query String 이해하기

[React] React Query 기본 사용법 정리