Open In App

ReactJS useContext Hook

Improve
Improve
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:



Last Updated : 13 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads