본문 바로가기

카테고리 없음

NextJS Error: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component

Before 코드는
프로젝트 app 폴더 내의 Layout관련 코드이다. 이에 RecoilRoot를 심게 되면 "use client" 관련 에러가 등장한다.
임시방편으로 상단에 표시하긴 했지만, Layout에서 metadata를 생성하는게 가장 효율적이라고 하여 metadata를 Layout에 추가시 "use client"를 제거하라는 에러가 떴다.


이를 해결하기 위해 여러가지 방법을 찾아봤지만 답을 얻을수 없었다. 그러다가 우연히 NextJS docs 에서 해결방법을 찾았고, 하단 링크에서 참고하였다.

결론적으로는 Layout을 랩핑하는 코드를 작성하여 최상단에 "use client"를 작성하라는 의미였다. 참고하면 좋을것 같아 하단 코드를 남겼다.

참고링크: https://nextjs.org/docs/getting-started/react-essentials

'use client';
// Third-party
import { RecoilRoot } from 'recoil';

// UI
import { Mont } from '../styles/font';
import '../styles/globals.css';
import Head from 'next/head';
import { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
  icons: {
    icon: '/next.svg',
  },
};
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang='en'>
      <body
        className={`w-full h-full flex flex-col pt-[72px] text-black font-mont ${Mont.variable}`}
      >
        <RecoilRoot>{children}</RecoilRoot>
      </body>
    </html>
  );
}

After

// RootLayout

// UI
import { Mont } from '../styles/font';
import '../styles/globals.css';
import { Metadata } from 'next';
import Provider from './provider';

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
  icons: {
    icon: '/next.svg',
  },
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <Provider>
      <html lang='en'>
        <body
          className={`w-full h-full flex flex-col pt-[72px] text-black font-mont ${Mont.variable}`}
        >
          {children}
        </body>
      </html>
    </Provider>
  );
}

// Provider
'use client';
import React, { ReactNode } from 'react';
import { RecoilRoot } from 'recoil';

function Provider({ children }: { children: ReactNode }) {
  return <RecoilRoot>{children}</RecoilRoot>;
}

export default Provider;