Write a program to pass values to child using context in ReactJS ?
Last Updated :
30 Oct, 2023
Passing values to chile in react js is an important concept in react js. It simply can be achieved by using prop drilling but it is not the right way in case of big project. Hence we will pass the values to child using context in react js with the help of useContext Hook.
Prerequisites
Approach
To pass values to child using context in React JS 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 wherever the data is required in any component. It makes the code much more readable, leaner, and less complex.

Creating React Application
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
Project structure

Steps to pass values to child using 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.
Example: The user data stored in app.js is passed to child components using useContext hook for creating context.
JavaScript
// Filename - App.js
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: "300px",
margin: "20px auto",
};
function App() {
let data = {
theme: "light",
name: "Geek",
userId: "gfg249",
email: "[email protected]",
contactNumber: "+91 999999999",
noOfQuestionsSolved: 120,
codingStreak: 30,
};
return (
<userContext.Provider value={data}>
<div className="App">
<h1 style={{ color: "green" }}>
GeeksForGeeks
</h1>
<h2>Context API</h2>
<Component1 />
</div>
</userContext.Provider>
);
}
export default App;
JavaScript
// Filename - context/UserContext.js
import { createContext } from "react";
export const userContext = createContext({});
JavaScript
// Filename - components/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;
JavaScript
// Filenname - components/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;
JavaScript
// Filename - 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;
JavaScript
// Filename - 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;
JavaScript
// Filename - 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 run the following command.
npm start
Output: Our final app will be visible on http://localhost:3000/ on browser and will look something like this.

Similar Reads
How to pass props to ReactJS component that wrapped in variable ? To pass props to a React JS component that is wrapped in a variable we have to create some copy of the component that can be modified. As we can't access the props of that component and pass a required argument we can clone it to make the required element and use it in our application. Props: Props
2 min read
How To Pass Props From Parent to Child Component in ReactJS? ReactJS is a powerful library that helps developers build interactive user interfaces by breaking them into reusable components. One of the essential features of React is the ability to pass data between components using props. In React, props allow parent components to send data or functions to chi
3 min read
What is the use of React Context in React-Redux? React Context is a feature that React provides us to manage states required in multiple components. Redux is also a state management library and solves the same problem that React Context does but in a different way. In this article, we will see in detail what is react context, why and how to use it
5 min read
Vue.js Passing Data to Child Components with Props Vue.js is a progressive javascript framework for developing web user interfaces. It is a performant, approachable, and versatile framework. We can create Single Page Applications as well as Full Stack applications. It is built on top of HTML, CSS, and Javascript which makes it easier for developers
3 min read
How can you use useContext to consume values from a React context? ReactJS provides Context API to manage the state at a global level in your application. It acts as a container where you can store multiple states, and functions and access them from anywhere in the application by using the useContext hook. In this article, we are going to learn how to use the useCo
3 min read
How to pass multiple props in a single event handler in ReactJS? To pass multiple props in a single event handler in ReactJS we can create a function to handle the event that accepts multiple props or calls multiple methods. It is a normal task while creating a react project to perform multiple operations for some events. PrerequisitesReact JSReact JS PropsTo pas
2 min read
How to set Parent State from Children Component in ReactJS? To set the parent state from a child component, we use Reactâs unidirectional data flow. Instead of directly passing data, we pass a function that enables the child to send data back to set the parent state.Prerequisites:React JSuseState HookApproachTo set parent state from child component in React,
2 min read
Using the React Context API for Efficient State Management The React Context API is a robust feature announced in React 16.3. It offers a way to share data within components without passing props directly at all stages. This is specifically useful for global data that many components seek to access, like user authentication, theme, or language settings. Rat
5 min read
How To Use React Context In NextJS With Typescript? React introduced Context to simply managing global consistent states in application. In this article we will how to use React Context for consistent states across various components with Next.js, the most popular and widely used React meta framework, and with TypeScript or complete type safety.Prere
4 min read
How to Pass Value from One Child Component to Another in VueJS ? Vue.js is a JavaScript framework used in building powerful and beautiful user interfaces. The key feature of Vue.js is its component-based architecture that allows the developers to create reusable and modular components. In this article, we will learn how to pass value from one child component to a
3 min read