recoil 이란

광천·2023년 3월 25일
1

recoil 이란

전역상태 라이브러리

Atoms

useState처럼 상태 관리

const fontSizeState = atom({
  key: 'fontSizeState',
  default: 14,
});

function FontButton() {
  const [fontSize, setFontSize] = useRecoilState(fontSizeState);
  return (
    <button onClick={() => setFontSize((size) => size + 1)} style={{fontSize}}>
      Click to Enlarge
    </button>
  );
}

Selectors

atoms나 다른 selectors를 입력으로 받아들이는 순수 함수
상태를 계산 할 때 사용

const fontSizeLabelState = selector({
  key: 'fontSizeLabelState',
  get: ({get}) => {
    const fontSize = get(fontSizeState);
    const unit = 'px';

    return `${fontSize}${unit}`;
  },
});

get인자를 통해 다른 atom이나 selector에 접근 할 수 있따.

function FontButton() {
  const [fontSize, setFontSize] = useRecoilState(fontSizeState);
  const fontSizeLabel = useRecoilValue(fontSizeLabelState);

  return (
    <>
      <div>Current font size: ${fontSizeLabel}</div>

      <button onClick={setFontSize(fontSize + 1)} style={{fontSize}}>
        Click to Enlarge
      </button>
    </>
  );
}

atomFamily(options)

Selectors와 다른 점은 매개변수를 받을수 있다.

const myAtomFamily = atomFamily({
  key: ‘MyAtom’,
  default: selectorFamily({
    key: 'MyAtom/Default',
    get: param => ({get}) => {
      return computeDefaultUsingParam(param);
    },
  }),
});

useRecoilCallback(callback, deps)

useCallback과 비슷, 비동기적으로 상태 업데이트와 Snapshot에 접근하고 싶을때 사용
https://taegon.kim/archives/10126

출처

https://recoiljs.org/ko/docs/api-reference/utils/atomFamily

0개의 댓글