skip to Main Content

We were using react’s context API in our next.js 12 apps.

We want to upgrade to next.js 13.

We get this error:

react__WEBPACK_IMPORTED_MODULE_0__.createContext is not a function

For this code:

import React from 'react'

const SiteContext = React.createContext()

export default SiteContext

What should we do now? I can’t find resources online for this.

Also, we need the Context API on the server because SEO matters and we don’t want to render on the client.

3

Answers


  1. The issue is that you need the "use client" directive.

    The error is being suppressed because of your import statement. Change the import to import { useContext } from 'react' and you will get the following 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.

    Checkout the beta docs for more details, but basically, ALL components inside the app directory are server components. For client components, you need to use the directive.

    "use client"
    
    import React from 'react'
    
    const SiteContext = React.createContext()
    
    export default SiteContext
    
    Login or Signup to reply.
  2. Next 13 does not support the React Context API on the server is the issue. Considering SEO matters you would have to stick with the old apps/pages approach for now. I hope they support context soon.

    Login or Signup to reply.
  3. In app directory you create your context inside a client component. Because you will need useState,useEffect hooks. the way you crete context api is same as before. But you need to wrap top layout file with this context.

    export default function RootLayout({
      children,
    }: {
      children: React.ReactNode;
    }) {
      return (
        <html lang="en">
          <head />
          <body>
            <main>
              <AuthContext>
                <main>
                  {children}
                </main>
              </AuthContext>
            </main>
          </body>
        </html>
      );
    }
    

    AuthContext is a client component and wraps children. Normally client components cannot render server components but since we are using children prop, components inside children tree can be server components.

    the problem with context api on the app directory is any component that needs to reach context has to be a client component because it needs to use useContext hook.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search