Open In App

Purpose of the useContext hook

The useContext hook in React makes it easier for components to get data from the overall theme or settings of your app. In React, “context” is like a way to share information among different parts of your app without having to hand it down through each piece. So, useContext helps a component quickly grab that shared info and use it.

Purpose of useContext:

The below code briefly explains uses of useContext to directly access the value provided by MyContext without needing to pass it as a prop through the component hierarchy.

import React,
{
createContext,
useContext
} from 'react';

// Create a context with a default value
const MyContext = createContext('default value');

const ExampleContext = () => {
// Consume the context using useContext
const contextValue = useContext(MyContext);

return <p>{contextValue}</p>;
};

// In a parent component, provide a value to the context
const ParentComponent =
() => {
return (
<MyContext.Provider
value="Hello from Context!">
<ExampleContext />
</MyContext.Provider>
);
};
Article Tags :