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
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: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.
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.
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.AuthContext
is a client component and wrapschildren
. Normally client components cannot render server components but since we are usingchildren
prop, components insidechildren
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.