Search code examples
reactjsnext.jsserver-side-renderingreact-context

Using React.Context with Nextjs13 server-side components


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?


Solution

  • It seems like I can use createServerContext

    import { createServerContext } from 'react';
    

    If you're using Typescript and React 18, you'll also need to add "types": ["react/next"] to your tsconfig.json compiler options, since this is a not-yet-stable function.