Open In App

ReactJS useContext Hook

Last Updated : 13 Jul, 2022
Like Article

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. 


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:



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



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 = () => {
  return (
      <AuthContext.Provider value={{ status: authstatus, login: login }}>
        <Auth />
export default App;



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);
  return (
      <h1>Are you authenticated?</h1>
      {auth.status ?
<p>Yes you are</p>
      <button onClick={auth.login}>Click To Login</button>
export default Auth;


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads