episyche logo

Episyche

NextJS/Context API/

How to use Context API in a Nextjs APP

Published on

How to use Context API in a Nextjs APP
Context API makes it possible to pass data from parent to child components. Integration of the Context API method into the Next js Application is explained here.

Introduction :

Context API :

Context is used to share the data between React components. Context API is one of the state management tools bundled with the React.js library itself. Context provides a way to pass data through the component tree without having to pass props down manually at every level

Flow Diagram:

 

flow diagram

Prerequisites :

  • Next.js

Steps:

Step 1: Create a context.js file.

  • If you already have the Next.js project, please copy the project and create a folder with your preferred name (e.g. context). In this blog, we are using a sample next.js project code with Tailwind CSS.

  • Inside the context folder, create a filename with a .js extension with your preferred name (e.g. context.js). As shown in the following screenshot.



folder structure

Step 2: Create the Context and manipulate the Context

In the context.js file. Import the modules required for your projects in the first line, In this example, we are using createContext and useState modules, so we have imported the same here, using the following snippet.

1import { createContext, useState } from "react";

and create a Context with the specific name, using the following snippet.

1export const Message_data = createContext(null);

and create a function with the props name. using the following snippet.

1 function Context({ children }) { 2 const [message, setMessage] = useState(); 3 4 return ( 5 <Message_data.Provider value={{ message, setMessage }}> 6 {children} 7 </Message_data.Provider> 8 ); 9}

As shown in the following screenshot.


create the context


A sample context.js file can be found in the following git repository file.

Step 3: Add the Context in _app.js to enable data sharing among all the components.

nextjs_context_api_example → pages →_app.js

  • Update the _app.js in the above path,

  • For this example we are using the Context file, so we have imported the same here. using the following snippet.

1import Context from "../context/context"
  • The imported Context is wrapped around the main component.

  • It is important to note that the context values are accessible inside the child component enclosed by the Context

  • Any component outside the Context will not be able to access the context values.

1function MyApp({ Component, pageProps }) { 2 return( 3 <> 4 <Context> 5 <Component {...pageProps} /> 6 </Context> 7 </> 8 ) 9} 10 11export default MyApp

As shown in the following screenshot.


set context in global


A sample _app.js file can be found in the following git repository file.

Step 4: Set the value in Context

nextjs_context_api_example → pages →index.js

  • For this example, we are using the useContext, useRouter, and context file. To know more about Next Routing click here.

  • so we have imported the same here in the above path. using the following snippet.

1import { Message_data } from "../../context/context"; 2import { useContext } from "react"; 3import { useRouter } from "next/router";

After importing all modules, use the useContext Hooks to set a value. To know more about React Hooks click here.

1const { message, setMessage } = useContext(Message_data);

If you want to access the router object inside any function component in your app, you can use the useRouter hook, using the following snippet.

1const router = useRouter();

In this sendData function, we get a value from input and set the value in Context, using the following snippet.

1 function sendData() { 2 var data = document.getElementById("context_id").value; 3 setMessage(data); 4 }

In this example create a simple header for routing with pages. and also Create the input field and send button. using the following snippet.

1 return ( 2 <> 3 <header> 4 <div className="bg-indigo-100 py-8 flex"> 5 <div onClick={() => router.push("/")} 6 className="mx-16 font-bold text-xl text-gray-600 cursor-pointer"> 7 first component 8 </div> 9 <div onClick={() => router.push("/share")} 10 className="mx-2 text-xl font-bold text-gray-600 cursor-pointer"> 11 second component 12 </div> 13 </div> 14 </header> 15 <section> 16 <div className="py-8 px-16"> 17 <h1 className="text-xl text-gray-600 my-4">Enter your content to pass another component</h1> 18 <input type="text" id="context_id" className="border rounded border-gray-600 py-1 w-96"></input> 19 <div> 20 <button onClick={() => sendData()} 21 className="w-fit border bg-green-600 text-white py-1 px-4 rounded font-bold my-4 hover:bg-green-700 22 cursor-pointer"> 23 send 24 </button>{" "} 25 </div> 26 </div> 27 </section> 28 29 </> 30 );/> 31 );


set value to the context


A sample index.js file can be found in the following git repository file.

Step 5: Retrieve data from Context

nextjs_context_api_example → pages

  • Inside the pages folder, creates a filename with a .js extension with your preferred name (e.g. Share.js ). As shown in the following screenshot.



folder structure

nextjs_context_api_example → pages→Share.js

  • Update the Share.js in the above path.

  • For this example, we are using the Context file, useRouter, and useContext so we have imported the same here. using the following snippet.

1import { Message_data } from "../../context/context"; 2import { useContext } from "react"; 3import { useRouter } from "next/router";

After importing all modules, use the useContext Hooks to get a value. using the following snippet. To know more about React Hooks click here.

1 const { message } = useContext(Message_data); 2 var router = useRouter();

Inside the return set the Context State to retrieve the value. using the following snippet.


coed structure

Step 6: Run your Application

Run the Next Application with the following command.

1npm run dev

After compiling your application open your browser and check the following URL:

1http://localhost:3000/

Result:

  • The Example UI is shown in the following screenshot.



exam UI page

 

  • In the Input enter the text and click the send button



send data to context

 

  • After clicking send button the data is stored in the context API.

  • And click on the second component in the header. after clicking, the page routes to another component



view in another component

  • In the second component, the data was shared via context API from the first component and retrieved the value.

  • A Sample GitHub repo, with all the required configurations, is given below.

Comments