본문 바로가기
TIL

[TIL] 2023.05.19 Next.js 13버전에 Recoil 적용하기

by heereal 2023. 5. 19.

Root Layout에 바로 RecoilRoot를 넣으려고 했더니 에러가 발생했다.

 

TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it.

RecoilRoot를 사용하려면 서버 컴포넌트를 클라이언트 컴포넌트로 변경해야 하는 거 같다. 하지만 Root Layout 파일을 클라이언트로 변경하면 모든 컴포넌트가 클라이언트 컴포넌트로 변경되는 결과가 생길 거 같아서 recoil 파일을 따로 빼서 적용하기로 했다.

 

'use client'

import { ReactNode } from 'react'
import { RecoilRoot } from 'recoil'

type Props = {
  children: ReactNode
}

export default function Recoil({ children }: Props) {
  return <RecoilRoot>{children}</RecoilRoot>
}

Recoil.tsx 파일을 생성한 후에 여기서 RecoilRoot를 import 한다.

 

그리고 Root Layout에서는 상단에서 생성한 Recoil 컴포넌트를 import 해서 하위 컴포넌트를 감싸준다. 이렇게 하면 Root Layout 파일을 전부 클라이언트 컴포넌트로 변경하지 않고 recoil 초기 세팅이 가능하다.

 

참고 

https://velog.io/@gwak2837/Next.js-13-프론트엔드-구성하기#recoil-react-query-react-toast-react-form

 

댓글