Web/React.js

Recoil

helperwoo 2024. 4. 5. 13:39
반응형

사용목적

React 컴포넌트는 공통된 상위 요소까지 끌어올려야만 공유될 수 있기에 거대한 트리가 다시 렌더링 되는 상황이 존재한다. Recoil은 React 자체 내장된 상태 관리 기능의 한계를 개선하기 위해 사용한다.

 

장점

  • get/set 인터페이스로 사용할 수 있도록 boilerplate-free API를 제공
  • React 기능들과 호환 가능성을 갖음
  • 상태 정의가 점진적이고 분산되어 있어 코드 분할이 용이함
  • 컴포넌트 수정 없이 상태(Atom)를 파생된 데이터(Selector)로 대체 가능

 

설치

npm install recoil

 

사용

RecoilRoot

Recoil 상태 컴포넌트를 부모 트리에 넣어준다. 예제는 루트 컴포넌트를 활용한다.

import React from 'react';
import { RecoilRoot, atom, selector, useRecoilState, useRecoilValue } from 'recoil';

function App() {
  return (
    <RecoilRoot>
      <CharacterCounter />
    </RecoilRoot>
  );
}

 

Atom

Atom은 상태의 일부를 나타낸다. atom을 사용하는 컴포넌트는 암묵적으로 atom을 구독한다. 상태 변경 시 atom을 구독한 모든 컴포넌트는 다시 렌더링 된다.

const textState = atom({
  key: 'textState', // unique ID (with respect to other atoms/selectors)
  default: '', // default value (aka initial value)
});

 

Selector

Slector는 파생된 상태를 정의한다. 즉, Atom에 의해 관리되는 상태 값(들)을 동적으로 가공할 수 있다. atom의 상태 변경 시 selector도 즉시 반영된다. 예제는 Atom의 text 값의 길이를 관리한다.

const charCountState = selector({
  key: 'charCountState', // unique ID (with respect to other atoms/selectors)
  get: ({get}) => {
    const text = get(textState);

    return text.length;
  },
});

 

반응형