useContext Hook
Context enables passing data/state through the component tree without manual prop passing. It’s for sharing global data like user authentication or theme. Context API uses Provider and Consumer components, but it’s verbose. useContext hook, introduced in React 16.8, makes code more readable and removes the need for Consumers.
Syntax:
const authContext = useContext(initialValue);
Example: Below is the code example for the useContext Hook:
Javascript
//App.js 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; |
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; |
Javascript
//auth-context.js import React from 'react' ; // Creating the context object and passing the default values. const authContext = React.createContext({status: null ,login:()=>{}}); export default authContext; |
Steps to Run the App:
npm start
Output:
Context Hooks in React
Context Hooks are a feature in React that allows components to consume context values using hooks. Before Hooks, consuming context required wrapping components in Consumer
or using a Higher Order Component (HOC). Context Hooks streamline this process by providing a more intuitive and concise way to access context values within functional components.
We will learn about the following concepts of Context Hooks in React
Table of Content
- Understanding Context Hooks in React
- Key Context Hooks
- Benefits of Context Hooks
- useContext Hook