Recoil

  1. Recoil이란?
    1. Global State 문제점
      1. Global State 예시
    2. Recoil 사용하기(with atom)
      1. useRecoilState
      2. useRecoilValue
    3. Selector
      1. get
      2. set
    4. Recoil Persist

Recoil

Recoil이란?

  • state를 atom에 넣어서 관리하게 하는 라이브러리.

Recoil 원리 예시
Atoms

Global State 문제점

Global State의 문제점
위와 같이 Global State를 사용할 때는 value를 이용하려면 연결된 Component마다
value를 부여해야 했지만 Recoil을 통하여 value를 편리하게 사용할 수 있다.

이미지 출처: React Europe Youtube

Global State 예시

Global State Ex1 Global State Ex2 Global State Ex3 Global State Ex4

Recoil 사용하기(with atom)

🛠️ npm install recoil

atoms.ts ```js import { atom } from “recoil”;

export const isDarkAtom = atom({ key: “isDark”, default: true, });


> index.tsx
```js
root.render(
  <RecoilRoot>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </RecoilRoot>
);

chart.tsx ```js function Chart({ coinId }: ChartProps) { const isDark = useRecoilValue(isDarkAtom); const { isLoading, data } = useQuery<IHistorical[]>([“ohlcv”, coinId], () => fetchCoinHistory(coinId) );

return ( … )}


### value 수정하기 : useSetRecoilState()
```js
function Coins({}: ICoinsProps) {
  const setDarkAtom = useSetRecoilState(isDarkAtom);
  const toggleDarkAtom = () => setDarkAtom((prev) => !prev);
  const { isLoading, data } = useQuery<ICoin[]>(["allCoins"], fetchCoins);
  return (
    <Container>
      <Helmet>
        <title>To the Moon ☽</title>
      </Helmet>
      <Header>
        <Title>To the Moon ☽</Title>
        <button onClick={toggleDarkAtom}>Ligth/Dark Mode</button>
      </Header>
      ...
  )
}

=> useState와 비슷하게 “useSetRecoilState”를 사용하면 된다.
⚠️ Atom은 함수인 것을 유의하자!


useRecoilState

useRecoilValue

Selector

  • state를 입력 받은 것을 변형해 반환하는 함수.

get

  • 원하는 atom을 가져 올 수 있다.

    set

  • state를 수정할 수 있게 한다. ```js export const minuteState = atom({ key: “minutes”, default: 0, });

export const hourSelector = selector({ key: “hours”, get: ({ get }) => { const minutes = get(minuteState); return minutes * 60; }, set: ({ set }, newValue) => { const minutes = Number(newValue) / 60; set(minuteState, minutes); }, });

function TimeConverter() { const [minutes, setMinutes] = useRecoilState(minuteState); const [hours, setHours] = useRecoilState(hourSelector); const onMinutesChange = (event: React.FormEvent) => setMinutes(+event.currentTarget.value); const onHoursChange = (event: React.FormEvent) => setHours(+event.currentTarget.value);

return ( <div> <h1>Time Converter</h1> Hours <input value={minutes} onChange={onMinutesChange} type=”number” placeholder=”시간” /> Minutes <input value={hours} onChange={onHoursChange} type=”number” placeholder=”분” /> </div> ); } ```

Recoil Persist

  • Local Storage에 저장하는 것을 도와주는 라이브러리.