How to create context in a React Server Component in Next.js
In this tutorial, you will learn how and why we must create context in a React Server Component in Next.js. Two objectives of this tutorial are:
- Why must we create a context in the React Server Component in Next.js?
- How to create context in a React Server Component in Next.js?
So, let’s get started.
Why must we create context in the React Server Component in Next.js?
In the usual scenario, we pass the data from one component to another using props. Something like this example:
Sender Component:
import Component1 from '..some location of component1'; const Component1=()=>{ const mydata={"Name":"Codespeedy"}; return ( <Component2 data={mydata}/> ) }
Receiver Component:
const Component2=({data})=>{ console.log("Hey I have got the data from component-1: ",data); return ( <Some HTML code here/> ) }
What’s the problem with this technique? So, here is the problem. Suppose, I want to pass the data from Component2 to some Component3, then to Component4, It will be very difficult and complex to handle this code, Here comes the Context feature to rescue. So, let’s understand it deeply.
How to create context in a React Server Component in Next.js?
Here is a problem, we cannot create context in the server component, Although we can create it in the client-side component. But in the case of the Server component it gives the error like this, Try it out:
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.
Step-1: create MyContext.js
Create a MyContext.js
file in your src/app/folder name.
Step-2: use client
We mention the “use client” directive at the top of the file which indicates that this is a client component, which is essential for the hook to function properly.
MyContext.js file
"use client" import { ReactNode, createContext, useContext } from "react"; const BlogContext = createContext({}); export function BlogProvider({ children }: { children: ReactNode }) { const value = { hello: "world" }; return ( <BlogContext.Provider value={value}>{children}</BlogContext.Provider> ); }
Step-3: wrapping the layout.js
Now wrap the layout.js
(.jsx/.tsx) (server component) with the provider to make the states available to the components and use them easily.
// layout.js import BlogProvider from './MyContext.js' export default function RootLayout({ children }) { return ( <html> <body> <BlogProvider>{children}</BlogProvider> </body> </html> ) }
Conclusion
Here we understood how and why we need to create context in a React Server Component in Next.js. I hope your concept is clear now.
Happy Learning!
Leave a Reply