본문 바로가기

Web Tech/library

Recoil

Recoil

리액트의 상태를 이용해 화면의 변화(Context API가 있긴 하지만 페이스북에서는 Context API를 이용해 상태를 관리하는 방식은 어렵다고 판단)를 줄 수 있지만 프론트엔드의 프로젝트가 점점 커지면서 그 상태가 너무 많아졌다. 
그래서 상태를 체계적으로 관리해야 하는 필요성을 느껴서 상태 관리 라이브러리가 나오게 되었다.
그 중 리코일은 리액트만을 위한 상태 관리 라이브러리다.


RecoilRoot 배치

recoil 상태를 사용하는 컴포넌트는 부모 트리 어딘가에 나타나는 RecoilRoot 가 필요하다. 

  • next.js -> _app.tsx
  • react => app.js
return (
    <>
      <Head>
        <title>YM ADMIN</title>
      </Head>
      <QueryClientProvider client={queryClient}>
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <SnackbarProvider
            autoHideDuration={3000}
            dense
            disableWindowBlurListener
            anchorOrigin={{ horizontal: "center", vertical: "top" }}
          >
            <RecoilRoot>
              <ErrorBoundary>
                <Suspense fallback={<Loading visibility />}>
                  {getLayout(<Component {...pageProps} />)}
                  <AlertModal />
                  <Box
                    id="draggable-potal"
                    style={{
                      position: "fixed",
                      pointerEvents: "none",
                      width: "100%",
                      height: "100%",
                      top: 0,
                      zIndex: 99999,
                    }}
                  />
                </Suspense>
              </ErrorBoundary>
            </RecoilRoot>
          </SnackbarProvider>
        </ThemeProvider>
        <ReactQueryDevtools />
      </QueryClientProvider>
    </>
  );

 


Atom 설정

Atom은 상태(state)의 일부를 나타내며,  어떤 컴포넌트에서나 읽고 쓸 수 있다. atom의 값을 읽는 컴포넌트들은 구독할 수 있고 

Atom의 상태가 변경되면 구독하고 있는 컴포너트들의 다시 랜더링되면서 변경된 Atom의 상태를 공유한다.

 

Atom은 고유한 키값과 기본값을 가진다. 고유한 키값을 이용해서 필요한 컴포넌트에서 Atom를 사용할 수 있고 기본값은 초기값이 된다.

 

import { atom } from "recoil";
import { filterObject } from "@utils/object";

type SearchStateType = {
  [pageKey: string]: {
    [key: string]: any;
  };
};

export const searchState = atom<SearchStateType>({
  key: "searchAtom",
  default: undefined,
});

export const clearSearchValue = (values: SearchStateType, pathname: string) => {
  return filterObject<SearchStateType>(values, ([k]) => k === pathname);
};

사용하기

 

  • const recoilseValue = useRecoilValue(값) : 값만 가져오는 방식
  • const setUseRecoilValue = useSetRecoilState(value) : 뒤에 set만 가져와서 실행하는 방식
  • const [useRecoilValue, SetUseRecoilValue] = useState(vlaue); : 둘 다 가져오는 방식
  • const resetRecoilState = useResetRecoilState(value); : 기본값으로 초기화 시키는 기능

'Web Tech > library' 카테고리의 다른 글

React Query  (0) 2024.06.11
Formik & Yup  (1) 2024.06.10