Skip to content
Related Articles

Related Articles

Write a program to pass values to child using context in ReactJS ?

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 02 Mar, 2022

In this article, we will see how to pass values to children using context. 

Approach: We will use context API. It is a method to avoid prop-drilling into deeply nested components. Without context API, we pass props from the parent component all the way via subcomponents and finally to the child component, where it is required. Context API removes the prop-drilling in the subcomponents and it allows the child component to access the piece of data with the help of useContext() hook where ever the data is required in any component. It makes the code much more readable, leaner, and less complex.

Which hooks are involved?

The Context API in react involved 2 hooks.

The createContext() hook is responsible for creating a context. It represents the data that we want to store in the current react app. It takes a parameter of the type of data which it will hold in, below in the example we have used {} curly braces in order to denote that the data will be an object. The useContext() hook is responsible to consume the data of context. It takes a parameter which is a context and allows the react component to access the data which is available in the context.

There are two methods to access data:

  • Object destructuring.
  • Via the ‘.’ operator.

We have used Object destructuring as it allows only the data which is necessary to be in the component. After initializing the context we have to wrap the parent most component with a provider which will allow the child components to access the piece of data which is being stored in the context. It is done via the Provider property of the usercontext ( or any other context which we have initialized previously ) and passes the piece of data in the value property of Provider.

Steps to use Context API in react :

  • Create a context initializing with the type of data it will hold ( it is an empty object in this case ).
  • Provide the context to the main file, so that the children are able to access the context data via useContext() hook.
  • Use the required properties of context in specific components.

Creating React Application And Installing Module:

Step 1: Create a React application using the following command.

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Step 3: After creating the ReactJS application, run the development server by following command:

npm start

Step 4: Create two folders in the src folder of react app i.e. components and context they will store the components of our app and the context respectively. It is a good practice to divide the app into sections and not just put all the files in one folder. Below is the image of the project structure.

Project structure:

Step 5: Create a UserContext.js file in the context folder and add the following code. Here we are creating a context that is similar to a store and export it so that the components which require or want to access the global data can subscribe to it. Also note it is initialized with an empty object denoted by ‘{}’.

UserContext.js




import { createContext } from "react";
export const userContext = createContext({});

Now we will be creating the files in a top to bottom fashion.

Step 6: Create a Component1.js file in the components folder and the following code. Now here we have added some basic styles in the App component and have some dummy data in the form of an object with some properties like theme, name , userId, and so on. Now for the children components to subscribe or get access to the global data we need to wrap the parent component with the context provider which we created in the previous step and pass the data which we want the children components to access by the property ‘ value ‘.

Javascript




import "./App.css";
import Component1 from "./components/Component1";
import { userContext } from "./context/UserContext";
  
export const mainStyle = {
  backgroundColor: "#4E9F3D",
  padding: "10px",
  borderRadius: "10px",
  boxShadow:
    "rgba(0, 0, 0, 0.3) 0px 19px 38px, rgba(0, 0, 0, 0.22) 0px 15px 12px",
  width: "200px",
  margin: "auto",
};
  
function App() {
  let data = {
    theme: "light",
    name: "Aman",
    userId: "aox01",
    email: "aman1@gmail.com",
    contactNumber: "+91 9898987231",
    noOfQuestionsSolved: 120,
    codingStreak: 30,
  };
  
  return (
    <userContext.Provider value={data}>
      <div className="App">
        <h2>Context API</h2>
        <Component1 />
      </div>
    </userContext.Provider>
  );
}
  
export default App;

Step 7: Create a Component1.js file in the components folder with the following code. It is a child component of the App component and doesn’t forget to add it to the App component as done in previous code. Here we have applied the styles from the App component by importing it. Now assume we want to just display the name of the person currently logged in to our app. So we can destructure the name property from the useContext() hook bypassing the context created in the userContext.js file. In this way, we can subscribe to the global store or the context.

Component1.js




import React, { useContext } from "react";
import Component2 from "./Component2";
import Component3 from "./Component3";
import { mainStyle } from "./../App";
import { userContext } from "./../context/UserContext";
  
const Component1 = () => {
  const { name } = useContext(userContext);
  return (
    <div>
      <div style={mainStyle}>
        <h2>Component1</h2>
        <h3>Welcome</h3> <h3>Geek {name} </h3>
      </div>
      <div style={{ display: "flex", justifyContent: "space-around" }}>
        <Component2 />
        <Component3 />
      </div>
    </div>
  );
};
  
export default Component1;

Step 8: Create Component2.js file in components folder and add the following code. It is just a child component of Component1 and where we want to display some data but no user information. Don’t forget to add this component into Component1.

Component2.js




import React from "react";
import Component4 from "./Component4";
import { mainStyle } from "./../App";
  
const Component2 = () => {
  return (
    <div style={mainStyle}>
      <h2>Component-2</h2>
      <p>Performance status at GeeksForGeeks</p>
      <Component4 />
    </div>
  );
};
  
export default Component2;

Step 9: Create Component3.js file in components folder and add the following code. It is just a child component of Component1 and where we want to display some data but no user information. Don’t forget to add this component into Component1.

Component3.js




import React from "react";
import { mainStyle } from "../App";
import Component5 from "./Component5";
  
const Component3 = () => {
  return (
    <div style={mainStyle}>
      <h2>Component3</h2>
      <p>Geek's personal information</p>
      <Component5 />
    </div>
  );
};
  
export default Component3;

Step 10: Create Component4.js file in components folder and add the following code. It is a child component of Component2 and where we want to display some user information only. Don’t forget to add this component into Component2. Like in Component1 we can subscribe to the context data by destructuring the noOfQuestionsSolved and codingStreak properties.

Component4.js




import React, { useContext } from "react";
import { userContext } from "./../context/UserContext";
  
const Component4 = () => {
  const { noOfQuestionsSolved, codingStreak } = useContext(userContext);
  
  return (
    <div>
      <h2>Component4</h2>
      <h3>
      Total number of Questions solved </h3> <h3>{noOfQuestionsSolved} 
      </h3>
      <h3>Coding streak</h3>
      <h3>{codingStreak} Days </h3>
    </div>
  );
};
  
export default Component4;

Step 11: Create Component5.js file in components folder and add the following code. It is a child component of Component3 and where we want to display some user information only. Don’t forget to add this component into Component3. Like in Component1 we can subscribe to the context data by destructuring the email and contactNumber properties.

Component5.js




import React, { useContext } from "react";
import { userContext } from "./../context/UserContext";
  
const Component5 = () => {
  const { email, contactNumber } = useContext(userContext);
  
  return (
    <div>
      <h2>Component5</h2>
      <h3>Email </h3>
      <h3>{email}</h3>
      <h3>Contact Number</h3> <h3> {contactNumber} </h3>
    </div>
  );
};
  
export default Component5;

Step to run application: Open the terminal and type the following command.

npm start

Output: Our final app will look something like this.

App structure:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!