Open In App

How to implement useContext Hook in a Functional Component ?

In React, the useContext hook is used to consume values from a context. Context in React is a way to share values like themes, authentication status, or any other global state between components without explicitly passing the props through each level of the component tree.

Syntax of useContext Hook:

const authContext = useContext(initialValue);

Steps to implement useContext Hook in React App:

Step 1: Create a React application using the following command:



npx create-react-app react-app

Step 2: After creating your project folder, i.e., react-app, move to it using the following command:

cd react-app

Project Structure: It will look like the following:



File Structure

The updated dependencies in the package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"run": "^1.4.0",
"web-vitals": "^2.1.4"
}

Approach to implement useContext Hook in Functional Component:

Example: Below is the code showing the example of use of the useContext to display the value from the context.




/* App.css */
 
body {
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      height: 100vh;
}
 
.main{
      color: green;
}
 
h2{
      color: blue;
}




// App.js
 
import React, { createContext, useContext } from 'react';
import './App.css'
 
// Create a context
const MyContext = createContext();
 
// Create a provider component
const MyProvider = ({ children }) => {
      const value = "Hello! This is from Context!";
      return <MyContext.Provider value={value}>{children}</MyContext.Provider>;
};
 
// Functional component that uses the context
const MyComponent = () => {
    // Use the useContext hook to access the context value
    const contextValue = useContext(MyContext);
 
   return (
     <div>
        <h1 className='main'>GeeksForGeeks </h1>
        <h2>Example of UseContext</h2>
        <h1>{contextValue}</h1>
     </div>
  );
};
 
const App = () => {
  return (
     <MyProvider>
       <MyComponent />
     </MyProvider>
  );
};
 
export default App;

To Run the Application, type the following command in terminal:

npm start

Output: Type the following link in your browser http://localhost:3000/

Implementing useContext Hook in a Functional Component


Article Tags :