The Wayback Machine - https://web.archive.org/web/20240717024440/https://www.geeksforgeeks.org/reactjs-usecontext-hook/
Open In App

ReactJS useContext Hook

Last Updated : 13 Jul, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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 uses Context. Provider and Context. Consumer Components pass down the data but it is very cumbersome to write the long functional code to use this Context API. So useContext hook helps to make the code more readable, less verbose and removes the need to introduce Consumer Component. The useContext hook is the new addition in React 16.8. 

Syntax:

const authContext = useContext(initialValue);

The useContext accepts the value provided by React.createContext and then re-render the component whenever its value changes but you can still optimize its performance by using memoization.

Example: Program to demonstrate the use of useContext Hook. In this example, we have a button, whenever we click on the button the onClick handler is getting triggered and it changes the authentication status(with a default value to Nopes) with the help of the useContext hook. Let’s see the output of the above code:

auth-context.js

Javascript




import React from 'react';
 
// Creating the context object and passing the default values.
const authContext = React.createContext({status:null,login:()=>{}});
 
export default authContext;


App.js

Javascript




import React, { useState } from "react";
import Auth from "./Auth";
import AuthContext from "./auth-context";
 
const App = () => {
  //using the state to dynamicallly pass the values to the context
 
  const [authstatus, setauthstatus] = useState(false);
  const login = () => {
    setauthstatus(true);
  };
  return (
    <React.Fragment>
      <AuthContext.Provider value={{ status: authstatus, login: login }}>
        <Auth />
      </AuthContext.Provider>
    </React.Fragment>
  );
};
export default App;


Auth.js

Javascript




import React, { useContext } from "react";
import AuthContext from "./auth-context";
 
const Auth = () => {
  // Now all the data stored in the context can
  // be accessed with the auth variable
  const auth = useContext(AuthContext);
  console.log(auth.status);
  return (
    <div>
      <h1>Are you authenticated?</h1>
      {auth.status ?
 
<p>Yes you are</p>
 
 :
 
<p>Nopes</p>
 
}
 
      <button onClick={auth.login}>Click To Login</button>
    </div>
  );
};
export default Auth;


Output:

Image



Similar Reads

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
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 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
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
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
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
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
ReactJS useReducer Hook
The useReducer Hook is the better alternative to the useState hook and is generally more preferred over the useState hook when you have complex state-building logic or when the next state value depends upon its previous value or when the components are needed to be optimized. The useReducer hook takes three arguments including reducer, initial stat
2 min read
Article Tags :
three90RightbarBannerImg