ReactJS useContext Hook

01 Nov, 2020
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 memorization.
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.jsJavascriptJavascriptimport React from 'react';  // Creating the context object and passing the default values.const authContext = React.createContext({status:null,login:()=>{}});  export default authContext;
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.jsJavascriptJavascriptimport 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;
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.jsJavascriptJavascriptimport 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;
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:
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
How to float three div side by side using CSS?
ReactJS | Router
How to get character array from string in JavaScript?