Introduction
How does the Context API work?
At the core of the Context API is the createContext function, which creates a new context object. This context object contains two components: a Provider and a Consumer.
The Provider component allows components to subscribe to changes in the context. It also provides a value prop that can be used to pass data to any child components that need access to it.
The Consumer component is used to access the data passed down by the Provider component. It must be used within the render method of a functional component or within the return statement of a class component.
Using the Context API in a React application
To use the Context API, you first need to create a context object using the createContext function. This context object can then be used to provide data to child components.
Example:
// Create a new context object
const MyContext = React.createContext();
// Define a provider component
function MyProvider(props) {
const [data, setData] = useState({});
return (
<MyContext.Provider value={{ data, setData }}>
{props.children}
</MyContext.Provider>
);
}
// Define a consumer component
function MyConsumer(props) {
return (
<MyContext.Consumer>
{({ data, setData }) => <div>{data}</div>}
</MyContext.Consumer>
);
}
// Use the provider and consumer components in your app
function MyApp() {
return (
<MyProvider>
<MyConsumer />
</MyProvider>
);
}

0 Comments