-
[Recoil] Next.js + Recoil + typescript 적용하기프레임워크/React(NextJs) 2022. 5. 29. 22:13
Next.js를 typescript로 설치해줍니다
$ npx create-next-app@latest --typescript
recoil 모듈 설치
$ npm install recoil
pages/_app.tsx 파일에서 RecoilRoot를 불러와 Component를 감싸줍니다
import type { AppProps } from 'next/app'; import { RecoilRoot } from 'recoil'; import '../views/styles/globals.css'; const MyApp = ({ Component, pageProps }: AppProps) => { return ( <RecoilRoot> <Component {...pageProps} /> </RecoilRoot> ); }; export default MyApp;
recoil 상태 관리 파일 생성해서 아래 내용을 입력합니다
저는 src/store/blogStore.tsx 이라는 파일을 만들어서 작성했습니다
import { atom } from 'recoil'; export interface IListTypes { id: number; contents: string; } export const listState = atom<IListTypes[]>({ key: 'list', default: [ { id: 0, contents: '' } ] });
pages/blog.tsx
/* eslint-disable react-hooks/exhaustive-deps */ import type { NextPage } from 'next'; import { useEffect } from 'react'; import { GetServerSideProps, InferGetServerSidePropsType } from 'next'; import { useRecoilState } from 'recoil'; import { IListTypes, listState } from '@store/blogStore'; const Blog: NextPage = ({ data }: InferGetServerSidePropsType<typeof getServerSideProps>) => { const [writingList, setWritingList] = useRecoilState<IListTypes[]>(listState); useEffect(() => { setWritingList(data); }, [data]); return ( <> <div> <ul> {writingList.map((v, i) => ( <li key={v.id}>{v.contents}</li> ))} </ul> </div> </> ); }; export const getServerSideProps: GetServerSideProps = async (context) => { const data = [ { id: 1, contents: '첫번째 글' }, { id: 2, contents: '두번째 글' }, { id: 2, contents: '세번째 글' } ]; return { props: { data: data } }; }; export default Blog;
혹시 작업도중에 useRecoilState, useRecoilValue 등 recoil hook이 오류가 난다면
react component 함수 내에 선언이 되어있는지 확인해보시기 바랍니다
참고)
pages/blog.tsx 파일에서 작성된 코드는 recoil이 적용된 것을 보기 위해 작성된 코드 입니다.
실제로는 recoil에 데이터를 넣지 않고 getServerSideProps로 받아온 data를 바로 map으로 돌려 보여줄 수 있습니다.
'프레임워크 > React(NextJs)' 카테고리의 다른 글
[React] react-hook-form(feat. typescript)으로 Input 컴포넌트 만들어보기 (0) 2022.09.06 [React] webpack 설정 (실시간 개발 모드 관련) (0) 2022.09.03 [React] .env (환경변수파일) - 'create-react-app'과 'webpack 빌드' 프로젝트에서의 각 설정 및 사용 방법 (0) 2022.09.03 [React] React + typeScript + webpack 설정으로 프로젝트 만들기 (0) 2022.06.09 [React] react-select 라이브러리와 onChange event 함수 (0) 2021.06.22