episyche logo

Episyche

React/Context API/

How to use Context API in a Reactjs APP?

Published on

How to use Context API in a Reactjs APP?
Context API makes it possible to pass data from parent to child components. Integration of the Context API method into the React 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 :

  • React.js

Steps:


Step 1: Create a context.js file.

reactjs_context_api_example → src

  • If you already have the React.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 React.js project code with Tailwind CSS.

  • Inside the context folder, creates a filename with a .js extension for example context.js. As shown in the following screenshot.



folder structure

Step 2: Create the Context and manipulate the Context

reactjs_context_api_example → src →context →context.js

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 context.js in the above path, using the following snippet.

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

and creates the context with the specific name using the following snippet.

1export const Message_data = createContext(null);

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

1function 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 index.js to enable the data sharing among all the components.

reactjs_context_api_example → src →index.js

  • Update the _app.js in the above path,

  • For this example, we are using the BrowserRouter, and Context file, so we have imported the same here. using the following snippet. To know more about React Routing click here.

1import Context from "./context/context"; 2import { BrowserRouter } from "react-router-dom";
  • The imported Context is wrapped around the App 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.

1const root = ReactDOM.createRoot(document.getElementById("root")); 2root.render( 3 <React.StrictMode> 4 <Context> 5 <BrowserRouter> 6 <App /> 7 </BrowserRouter> 8 </Context> 9 </React.StrictMode> 10);

As shown in the following screenshot.


set context in global


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

Step 4: Create a pages folder

reactjs_context_api_example → src

  • Inside the src folder, create a folder with your preferred name (e.g. pages). in the above path

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


Step 5: Create a Header for routing

reactjs_context_api_example → src →App.js

  • Update the App.js in the above path

  • For this example, we are using the Routes, Route, and Link modules. so we have imported the same here. and also import the files inside the pages folder. using the following snippet.

1import { Routes, Route, Link } from "react-router-dom"; 2import Home from "./pages/Home"; 3import Second from "./pages/Second";

Inside the function, the component adds the header and React Routes. using the following snippet. To know more about React Routing click here.

1function App() { 2 return ( 3 <> 4 <header> 5 <div className="bg-indigo-100 py-8 flex"> 6 <div className="mx-16 font-bold text-xl text-gray-600 cursor-pointer"> 7 <Link to="/"> 8 first component 9 </Link> 10 </div> 11 <div className="mx-2 text-xl font-bold text-gray-600 cursor-pointer"> 12 <Link to="/second"> 13 second component 14 </Link> 15 </div> 16 </div> 17 </header> 18 <Routes> 19 <Route path="/" element={<Home />} /> 20 <Route path="/second" element={<Second />} /> 21 </Routes> 22 </> 23 ); 24}

As shown in the following screenshot.

Step 6: Send the Data to Context

reactjs_context_api_example → src→pages→Home.js

  • Update the Home.js in the above path.

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

1import { Message_data } from "../context/context"; 2import { useContext } from "react";

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

1 const { setMessage } = useContext(Message_data);

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 an input field and send button. using the following snippet.

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

As shown in the following screenshot.

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

Step 7: Retrieve data from Context

reactjs_context_api_example → src →Pages→Second.js

  • Update the Second.js in the above path.

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

1import { Message_data } from "../context/context"; 2import { useContext } from "react";

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

1const { message } = useContext(Message_data);

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

1 return( 2 <> 3 <h1 className="mx-16 text-xl my-12">{message}</h1> 4 </> 5 )

As shown in the following screenshot.

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

Step 8: Run your Application

Run the React Application with the following command.

1npm start

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.

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

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

  • And click on the second component in the header, and after clicking, the page route to 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