The Wayback Machine - https://web.archive.org/web/20240716122700/https://www.geeksforgeeks.org/how-can-you-use-usecontext-to-consume-values-from-a-react-context/
Open In App

How can you use useContext to consume values from a React context?

Last Updated : 15 Apr, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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 useContext hook with examples and syntax.

What is useContext?

useContext is a hook that provides a way to pass data through the component tree without manually passing props down through each nested component. It is designed to share data that can be considered global data for a tree of React components, such as the current authenticated user or theme(e.g. color, paddings, margins, font-sizes).

Approach to use useContext:

We have created a Globaldata context using the createContext() function and exported it to be used in other components. We have created a state to store the data and stored that state and its function in a react context by using <Globaldata.Provider value={{….}}>.

We are accessing this react context in a child component by using useContext hook as a function and we are passing our Globaldata context that we have created in a parent component.

Syntax:

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

To provide a react Context Data to Application (create this at root level component):

Syntax:

<ContextName.Provider value={{....}}>
      ...other components...
</ContextName.Provider>

To access Context data:

Syntax:

import { useContext } from "react";
import { ContextName } from "./component";
const { ...... } = useContext(ContextName);

Steps to Create React Application:

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

npx create-react-app gfg

Step 2: After creating your project folder(i.e. gfg), move to it by using the following command:

cd gfg

Project Structure:

useContext-project-structure

Example: The below example is demonstrating the use of useContext hook in ReactJS

JavaScript
//src/App.js

import { createContext, useState } from "react";
import Child from "./Child";

export const Globaldata = createContext();

const App = () => {
    const [name, setName] = useState("GFG");

    return (
        <Globaldata.Provider value={{ name, setName }}>
            <span>Parent Component</span> <br />
            <button onClick={() => setName("GeeksForGeeks")}>
                Change Name to GeeksForGeeks
            </button>
            <hr />
            <Child />
        </Globaldata.Provider>
    );
};

export default App;
JavaScript
//src/Child.js

import { useContext } from "react";
import { Globaldata } from "./App";

const Child = () => {
    const { name, setName } = useContext(Globaldata);

    return (
        <>
            <span>Child Component</span> <br />
            <button onClick={() => setName("GFG")}>
                Change Name to GFG
            </button>
            <h1>Context Data: {name}</h1>
        </>
    );
}

export default Child;


To run the application use the following command:

npm run start

Output: Now go to http://localhost:3000 in your browser:

useContext



Similar Reads

Context API with useContext Hook
React Context API is a very helpful feature that enables the sharing of state across components without the need for prop drilling. It simplifies state management and makes it easier to pass data down the component tree. In this article we will explore the Context API and demonstrate how to use it with the "useContext" hook through practical exampl
3 min read
What's the role of the useContext hook in React Hooks?
The useContext hook in React Hooks allows you to consume values from the React context without needing to explicitly pass props through every level of your component tree. Role of useContext hook in React Hooks:Accessing Context Values:With useContext, you can access values stored in a React context from any component within the same context provid
2 min read
How does useContext help with sharing data between components in React?
useContext is a hook in React that facilitates the sharing of data between components without the need to pass props manually through every level of the component tree. It allows components to consume data from a context that has been defined higher up in the component hierarchy. How does it work?Centralized Data Storage:React context allows you to
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, how it is related to and different from react-re
5 min read
How to use React Context with React-Redux ?
React context with React-Redux is a popular state management library for React applications. Using React context with React-Redux is a powerful way to provide the Redux store to components deep within your component tree without manually passing it down through props. PrerequisitesNode.js and NPMReactReact-ReduxJavaScriptApproach:First, define a Re
3 min read
ReactJS useContext Hook
Context provides a way to pass data or state through the component tree without having to pass props down manually through each nested component. It is designed to share data that can be considered as global data for a tree of React components, such as the current authenticated user or theme(e.g. color, paddings, margins, font-sizes). Context API u
2 min read
What's the difference between useContext and Redux ?
In React, useContext and Redux both approaches provide ways to manage and share state across components. Both work and manage global data to share and access from any component present in the application DOM tree, but they have different purposes and use cases. Table of Content useContext ReduxDifference between useContext and ReduxuseContext useCo
5 min read
Purpose of the useContext hook
The useContext hook in React makes it easier for components to get data from the overall theme or settings of your app. In React, "context" is like a way to share information among different parts of your app without having to hand it down through each piece. So, useContext helps a component quickly grab that shared info and use it. Purpose of useC
2 min read
How to combine useContext with useReducer?
Combining useContext with useReducer in React allows you to manage a global state more effectively by providing a centralized state management solution. How to combine useContext with useReducer?Create a Context: First, you need to create a context to hold your global state and provide it to your component tree. You can use the React.createContext(
3 min read
Implementing Global State Management with useContext
The useContext hook is a powerful addition introduced in React 16.8. It allows you to share context (or some value) with all the child elements within a context provider. This is particularly useful when you want to access data or state in child components without manually passing props down to each nested component. In this article, you'll learn a
4 min read
Article Tags :
three90RightbarBannerImg