Recoil을 사용한 전역 상태 관리

woodylovesboota·2023년 9월 8일
0
post-thumbnail

State가 변하면 component를 re-rendering 하며 UI가 새롭게 그려지는 것처럼 state는 react를 사용하는 입장에서 에서 매우 중요한 역할을 담당한다.

하지만 다양한 component에서 동일한 state를 이용하기 위해서 props를 통해 state를 공유해 주어야만 하였다.

const App = () => {
  return(
    <>
      <Word answer={answer} />
      ...
    </>
  );
}
      
const Word = ({answer}) => {
  return (
    <>
      <Letter answer={answer} />
      ...
    </>
  );
}

이처럼 state를 하나하나 props를 통해 옮겨주면 개발하는 입장에서 매우매우 번거로운 작업을 해야한다. 또한 인접한 하위 컴포넌트가 아닌 더 아래에 있는 컴포넌트에서 state를 사용하고 싶은 경우에는 가운데 컴포넌트에서 불필요한 props 전달이 일어날 가능성이 있다.

이를 해결하기 위해 react 에는 전역으로 state를 관리할 수 있는 state management tool이 존재한다.

Redux 와 Recoil 두가지가 많이 쓰이는데 Recoil을 사용하여 state를 관리해보자.

Recoil


Recoil은 페이스북 팀에서 만든 state management library 라고 한다. 사용해본 입장에서 매우 쉽게 사용할 수 있다는 장점이 있다.

사용

가장먼저 recoil을 설치해준다

$ npm install recoil

Recoil을 사용하기 위해서는 모든 component가 RecoilRoot에 싸여있어야 한다. index.tsxRecoilRoot를 import 해주자.

import { RecoilRoot } from "recoil";

root.render(
  <RecoilRoot>
  	<App />
  </RecoilRoot>
);

이후 atoms.tsx라는 파일을 생성해주고 거기에 state에 대한 정보를 적으면 된다.

import { atom } from "recoil";

export const nameState = atom({
  key: "name",
  default: "",
});

이러면 기본값이 "" 인 state가 생성된 것이다. 이 state는 전역적으로 사용될 수 있고 따라서 props를 통해 component 끼리 state를 교환하는 과정이 필요하지 않다.

component에서 recoil state를 사용하기 위해서는 atoms.tsx를 import 해주면 된다.

import { nameState } from "./atoms";

Rcoil에서 state를 사용하는 방법은 useState와 비슷하다.

const [name, setName] = useRecoilState(nameState);

name은 state value, setName 은 modifier function 이다.

불필요한 코드를 줄이기 위해, 만약 component에서 value나 modifier function중 하나만 사용한다면 각각 useRecoilValue() , useSetRecoilState() 를 사용하면 된다.

이를 이용하여 component의 위치에 상관없이 Global 하게 state를 관리 할 수 있다.

전역적으로 state가 관리되는 지를 확인하기 위해 이름을 출력하는 app 을 만들어 보았다.

function App() {
  const [name, setName] = useRecoilState(nameState);
  return (
    <form>
      <h1>My name is {name}</h1>
      <Input />
    </form>
  );
}
const Input = () => {
  const [name, setName] = useRecoilState(nameState);
  return (
    <input
      onChange={(e) => {
        setName(e.currentTarget.value);
      }}
    ></input>
  );
};

Input에서는 state를 변경하고 App에서는 state를 출력하는 부분이 구현되어 있다. state가 제대로 관리되고 있다면 input에서 변경한 state가 바로바로 출력되어야 할 것이다.

State가 변경됨에 따라 전역적으로 browser가 달라지는 것을 확인 할 수 있다.

0개의 댓글

관련 채용 정보