FrontEnd, Recoil (class 내부에서 Recoil 사용불가)

Jihu Kim·2024년 12월 11일
0

FrontEnd

목록 보기
8/13
post-thumbnail

Recoil 함수

기본 단위

  • atom

    • 역할: 상태(State)의 가장 기본적인 단위.

    • 설명: 애플리케이션에서 독립적인 상태를 나타냄. atom으로 정의된 상태는 여러 컴포넌트에서 읽고, 업데이트할 수 있음.

    • 예제:

      import { atom } from 'recoil';
      
      export const counterState = atom({
        key: 'counterState', // 고유 키 (필수)
        default: 0,          // 초기값
      });
  • selector

    • 역할: 파생된 상태(Derived State)를 계산.

    • 설명: atom 상태나 다른 selector 상태를 기반으로 계산된 상태를 생성.
      캐싱을 지원하여 성능 최적화. 컴포넌트에서 읽기 전용 또는 동기/비동기 상태를 관리할 수 있음.

    • 예제:

      import { selector } from 'recoil';
      import { counterState } from './atoms';
      
      export const doubledCounterState = selector({
        key: 'doubledCounterState',
        get: ({ get }) => {
          const count = get(counterState);
          return count * 2; // counterState의 값에 2를 곱한 결과를 반환
        },
      });
    • 상태 비동기 관리

      import { selector } from 'recoil';
      
      export const fetchDataSelector = selector({
        key: 'fetchDataSelector',
        get: async () => {
          const response = awai fetch('https://api.example.com/data');
          const data = await response.json();
          return data;
        },
      });

Hooks

  • useRecoilState:

    • 역할: atom 상태를 읽고 업데이트.
    • 사용법:
      			const [count, setCount] = useRecoilState(counterState);
    • 설명: React의 useState와 비슷하지만, atom에 정의된 전역 상태를 사용.
  • useRecoilValue:

    • 역할: atom이나 selector의 값을 읽기 전용으로 가져옴.
    • 사용법:
      const doubledCount = useRecoilValue(doubledCounterState);
    • 설명: 값을 읽기만 할 때 적합.
  • useSetRecoilState:

    • 역할: atom의 상태를 업데이트.
    • 사용법:
      const setCount = useSetRecoilState(counterState);
      setCount((prev) => prev + 1); // 상태 업데이트
  • useResetRecoilState:

    • 역할: atom 상태를 초기값으로 리셋.
    • 사용법:
      const resetCount = useResetRecoilState(counterState);
      resetCount(); // 초기값으로 리셋

class 내부에는 Recoil을 사용할 수 없다?

Recoil의 상태 관리 메서드(useRecoilState, useRecoilValue, useSetRecoilState)는 React Hook으로 제공됩니다.
React Hook은 다음과 같은 이유로 class 내부에서 사용할 수 없습니다:

  • React Hook의 동작 방식
    • Hook은 React 함수형 컴포넌트 내부에서만 호출되어야 합니다.
    • 이는 React의 렌더링 흐름과 상태 관리 로직이 컴포넌트의 생명주기와 연결되어 있기 때문입니다.
    • 클래스 내부는 React 렌더링 흐름과 직접 연결되지 않으므로 Hook을 사용할 수 없습니다.
  • Hook의 규칙
    • Hook은 컴포넌트의 최상위 레벨에서 호출되어야 합니다.
    • 조건문이나 반복문 내부, 클래스 메서드에서는 Hook을 호출할 수 없습니다.
    • 이는 React가 상태 관리 순서를 추적하기 위해 필요합니다.
profile
Jihukimme

0개의 댓글