The Wayback Machine - https://web.archive.org/web/20240717024440/https://www.geeksforgeeks.org/implementing-global-state-management-with-usecontext/
Open In App

Implementing Global State Management with useContext

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 about useContext in depth.

What is Global State Management?

Global state refers to data that needs to be accessible across different components in your React application. Instead of passing props down through multiple levels of components (a process known as “prop drilling”), you can use the global state to share data efficiently. It eliminates the need for prop drilling and provides a cleaner way to manage shared state across components. You can consider useContext as a simple state as we create using useState. The only thing context will do is to share this state and its changes across the app.

Approach to Manage Global State with useContext hook:

To create a context in any React app, you need to follow 4 simple steps –

  1. Create a context: A context in React is a way to share data between components without having to pass it through props. It acts as a global state container.
  2. Create a provider: The provider is responsible for making the context data available to all the components that need it. You wrap your app (or a specific part of your app) with the provider component. This is typically done in your top-level component (like App.js).
  3. Add provider to the app: You wrap your app components with the context provider. Any component within this provider’s scope can access the shared data using the useContext hook.
  4. UseContext: The useContext hook allows components to use the context data. Import the context you created and use it within a component.

In simple words when we are creating a context, we are creating a state. And when we create a provider, as its name says, we are creating a wrapper component to provide that state to all the components.

Steps to Create React Application:

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

npx create-react-app global-state

Step 2: Move to the folder using the following command:

cd global-state

Project Structure:

dewrfgr

Folder Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example: Create the required files and add the following codes.

Javascript




//index.js
 
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { ThemeProvider } from './ThemeContext';
 
ReactDOM.render(
    <React.StrictMode>
        <ThemeProvider>
            <App />
        </ThemeProvider>
    </React.StrictMode>,
    document.getElementById('root')
);


Javascript




//App.jsx
 
import React from 'react';
import ThemeToggleButton from './ThemeToggleButton';
import './App.css';
 
const App = () => {
  return (
    <div className="app-container">
      <h1>GFG Theme</h1>
      <ThemeToggleButton />
      <p>Rest of the contents.</p>
    </div>
  );
};
 
export default App;


Javascript




//ThemeContext.js
 
import React, { createContext, useContext, useState } from 'react';
 
const ThemeContext = createContext();
 
export const useTheme = () => useContext(ThemeContext);
 
export const ThemeProvider = ({ children }) => {
    const [darkMode, setDarkMode] = useState(false);
 
    const toggleTheme = () => {
        setDarkMode(prevMode => !prevMode);
    };
 
    return (
        <ThemeContext.Provider value={{ darkMode, toggleTheme }}>
            <div className={darkMode ? 'dark' : 'light'}>{children}</div>
        </ThemeContext.Provider>
    );
};


Javascript




//ThemeToggleButton.js
 
import React from 'react';
import { useTheme } from './ThemeContext';
 
const ThemeToggleButton = () => {
    const { darkMode, toggleTheme } = useTheme();
 
    return (
        <button className="theme-toggle-button" onClick={toggleTheme}>
            {darkMode ? 'Switch to Light Theme' : 'Switch to Dark Theme'}
        </button>
    );
};
 
export default ThemeToggleButton;


CSS




/* App.css*/
.light {
    background-color: #ffffff;
    color: #000000;
}
 
 
.dark {
    background-color: #222222;
    color: #ffffff;
}
 
 
.theme-toggle-button {
    padding: 10px 20px;
    background-color: #007bff;
    color: #ffffff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}
 
.theme-toggle-button:hover {
    background-color: #0056b3;
}


To start the application run the following command.

npm start

Output:

Animation37

Output



Similar Reads

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
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
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
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
How to implement useContext Hook in a Functional Component ?
In React, the useContext hook is used to consume values from a context. Context in React is a way to share values like themes, authentication status, or any other global state between components without explicitly passing the props through each level of the component tree. Syntax of useContext Hook:const authContext = useContext(initialValue);Steps
2 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 useContext hook with examples and syntax. What is useCo
3 min read
Implementing State in React Components
In React State is an object that holds some information which can be changed overtime. Whenever a State is updated it triggers re-rendering of the component. In React components State can be implemented by default in class components and in functional components we have to implement state using hooks. Table of Content Approaches To Implementing Sta
3 min read
three90RightbarBannerImg