Context and useContext Hook
In React, the Context API is used for sharing data between components without passing props through every level.
The Context API comes with a hook called useContext that makes it easy to consume data from a context.
To create a context, you can use the createContext
method from the React
library:
1const MyContext = React.createContext();
2```+
3
4To provide a value to the context and make it available to child components, you can use the `Provider` component and pass the value as a prop:
5
6```javascript
7function App() {
8 const value = "Hello, World!";
9
10 return (
11 <MyContext.Provider value={value}>
12 {/* Child components here */}
13 </MyContext.Provider>
14 );
15}
To consume the context and access the value in a child component, you can use the useContext
hook:
1function ChildComponent() {
2 const value = React.useContext(MyContext);
3
4 return (
5 <div>{value}</div>
6 );
7}
In the example provided, we create a context MyContext
and provide a value of Hello, World!
using the Provider
component. Then, in the ChildComponent
, we consume the context using the useContext
hook and display the value.
Feel free to explore and experiment with the Context API and the useContext hook to efficiently manage global state and share data across multiple components.
xxxxxxxxxx
// Replace with your code
// Example of creating a context
const MyContext = React.createContext();
// Example of providing a value to the context
function App() {
const value = "Hello, World!";
return (
<MyContext.Provider value={value}>
<ChildComponent />
</MyContext.Provider>
);
}
// Example of consuming the context
function ChildComponent() {
const value = React.useContext(MyContext);
return (
<div>{value}</div>
);
}