React Context API
React Context API
React Context API is a way to pass data through the component tree without having to pass props down manually at every level. It provides a way to share values between components without having to explicitly wire them together.
Basic Usage
To use React Context API, we need to create a context object using the createContext
function. Then, we can use the Provider
component to wrap our top-level component and pass the context object as a prop.
import React, { createContext, useState } from 'react';
const MyContext = createContext();
function App() {
const [count, setCount] = useState(0);
return (
<MyContext.Provider value={{ count, setCount }}>
<Child />
</MyContext.Provider>
);
}
}
In the Child
component, we can use the useContext
hook to access the context object and its values.
import React, { useContext } from 'react';
function Child() {
const { count, setCount } = useContext(MyContext);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
In this example, we create a MyContext
object and pass it as a prop to the Provider
component. In the Child
component, we use the useContext
hook to access the count
and setCount
values from the MyContext
object. We can then update the count
state by calling the setCount
function.