ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Recoil] 공식 문서 selector(async) 예제 간단 풀이
    개발/React 2022. 8. 18. 00:10

    공식문서에 있는 예제입니다.

    import {atom, selector, useRecoilState, DefaultValue} from 'recoil';
    
    const tempFahrenheit = atom({
      key: 'tempFahrenheit',
      default: 32,
    });
    
    const tempCelcius = selector({
      key: 'tempCelcius',
      get: ({get}) => ((get(tempFahrenheit) - 32) * 5) / 9,
      set: ({set}, newValue) =>
        set(
          tempFahrenheit,
          newValue instanceof DefaultValue ? newValue : (newValue * 9) / 5 + 32,
        ),
    });
    
    function TempCelcius() {
      const [tempF, setTempF] = useRecoilState(tempFahrenheit);
      const [tempC, setTempC] = useRecoilState(tempCelcius);
      const resetTemp = useResetRecoilState(tempCelcius);
    
      const addTenCelcius = () => setTempC(tempC + 10);
      const addTenFahrenheit = () => setTempF(tempF + 10);
      const reset = () => resetTemp();
    
      return (
        <div>
          Temp (Celcius): {tempC}
          <br />
          Temp (Fahrenheit): {tempF}
          <br />
          <button onClick={addTenCelcius}>Add 10 Celcius</button>
          <br />
          <button onClick={addTenFahrenheit}>Add 10 Fahrenheit</button>
          <br />
          <button onClick={reset}>Reset</button>
        </div>
      );
    }

    실행해보면 섭씨와 화씨 값이 같이 올라갑니다. 처음에는 동작 방식이 잘 이해가 안 갔습니다.

    DefaultValue라는 것도 영 긴가민가했습니다.

    공식 문서를 보면 DefalutValue는 재설정 작업을 나타내는 객체라고 하는데요.

    useResetRecoilState를 사용하면 함수가 반환됩니다.

    이 함수를 호출하면 atom으로 State를 만들 때 설정한 default 값으로 초기화됩니다.

     

    다음 코드의 의미는 리셋을 할 때 default 값이 set 함수의 두 번째 인자인 newValue로 전달이 된다는 겁니다.

    set: ({set}, newValue) =>
        set(
          tempFahrenheit,
          newValue instanceof DefaultValue ? newValue : (newValue * 9) / 5 + 32,
        ),

    여기서는 32가 전달되겠죠. 

    그럼 tempFahrenheit의 상태값은 32으로 초기화되고, tempCelcius의 상태값은 0으로 초기화됩니다.

    set의 첫 번째 인자로 tempFarenheit를 전달하는데요.

    이는 tempFarenheit 상태를 변경한다는 뜻입니다.

    tempCelcius에서 tempFarenheit를 의존하고 있으므로

    tempFarenheit가 변경되면 tempCelcius의 get 함수가 호출됩니다.

     

    다시 한 번 설명해보겠습니다.

    버튼을 누를 때 두 값 모두 올라가는 이유는

    tempCelcius 상태가 tempFahrenheit 상태에 의존적이기 때문입니다.

    이 관계에서는 tempFahrenheit가 바뀌면 tempCelcius가 같이 바뀌는 이유가 명확합니다.

     

    그렇다면 setTempC로 섭씨 온도를 변경할 때는 어떻게 된 것일까.

    즉, 섭씨 온도를 올릴 때는 어떤 일이 일어날까요.

    setTempC 함수를 호출하면 tempCelcius의 set이 호출됩니다.

     

    set에서 tempFahrenheit의 상태를 변경하면

    이에 의존적인 tempCelcius의 get 함수가 실행되면서 read-only 속성인 tempC가 갱신됩니다.

     get: ({ get }) => ((get(tempFahrenheit) - 32) * 5) / 9,

    즉 섭씨 온도를 올리는 버튼을 클릭하면

    화씨가 먼저 갱신되고 나서 섭씨가 갱신됩니다.

    tempCelcius는 tempFahrenheit에 의존적이니까요.

    댓글

Designed by Tistory.