React useContext Hook
React useContext
'useContext' is a React Hook that allows you to subscribe to a context in a functional component.
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
Here's a basic overview of how 'useContext' works:
1.Create a Context:
First, you need to create a context using React.createContext. This creates a Context object, which comes with a Provider component and a Consumer component.
// MyContext.js
import { createContext } from 'react';
const MyContext = createContext();
export default MyContext;
1.Provide the Context:
Wrap your component tree with a Provider to make the context available to all components within that tree.
// App.js
import React from 'react';
import MyContext from './MyContext';
const App = () => {
const myData = "Hello from Context!";
return (
<MyContext.Provider value={myData}>
{/* Your component tree */}
</MyContext.Provider>
);
}
export default App;
3.Consume the Context using useContext:
In any component within the context provider, you can use the useContext hook to access the context value.
// MyComponent.js
import React, { useContext } from 'react';
import MyContext from './MyContext';
const MyComponent = () => {
const contextValue = useContext(MyContext);
return (
<div>
{contextValue}
</div>
);
}
export default MyComponent;
The 'useContext' hook takes the context object as an argument and returns the current context value.