react js-tutorial

React useContext

Without having to manually provide props down via each nested component, context offers a means to pass data or state through the component tree. For a tree of React components, it is intended to share information that can be regarded as global information, such as the currently authenticated user or theme (e.g. color, paddings, margins, font-sizes).

Context is used by Context API. Context and Provider Consumer Components transmit the data, however writing the lengthy functional code to leverage this Context API is quite time-consuming. Therefore, using the useContext hook eliminates the requirement to use the Consumer Component and makes the code easier to read and less verbose. React 16.8 has a new addition called the useContext hook.


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;



Leave a Reply

Your email address will not be published.