Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using React.Context with Nextjs13 server-side components [duplicate]

Next13 was released a week ago, and I am trying to migrate a next12 app to a next13. I want to use server-side components as much as possible, but I can't seem to use

import { createContext } from 'react';

in any server component.

I am getting this error:

Server Error
Error: 

You're importing a component that needs createContext. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.

   ,----
 1 | import { createContext } from 'react';
   :          ^^^^^^^^^^^^^
   `----


Maybe one of these should be marked as a client entry with "use client":

Is there an alternative here or do I have to resort to prop drilling to get server-side rendering?

like image 359
Tomer Almog Avatar asked Sep 05 '25 02:09

Tomer Almog


1 Answers

This is a new feature from React's SSR to recognize whether a component is client-side or server-side. In your case, createContext is only available on the client side.

If you only use this component for client-side, you can define 'use client'; on top of the component.

'use client';

import { createContext } from 'react';

You can check this Next.js document and this React RFC for the details

like image 194
Nick Vu Avatar answered Sep 08 '25 04:09

Nick Vu