React Context API - rs-hash/Learning GitHub Wiki
The Context API is a built-in feature in React that provides a way to manage global state and share data between components without having to pass props through multiple levels of the component tree. It allows you to create a Context object, which acts as a central store for data, and then use the Provider and Consumer components to access and update that data.
Let's go through a step-by-step explanation of the Context API with sample code:
Step 1: Create a Context Object
First, create a new context object using React.createContext().
// context.js
import React from 'react';
const MyContext = React.createContext();
export default MyContext;Step 2: Create a Provider Component
Wrap your application (or a specific part of it) with the Provider component, passing the data you want to share as a value prop.
// App.js
import React from 'react';
import MyContext from './context';
import ComponentA from './ComponentA';
function App() {
const sharedData = 'This data is shared using Context API';
return (
<MyContext.Provider value={sharedData}>
<div>
<h1>App</h1>
<ComponentA />
</div>
</MyContext.Provider>
);
}
export default App;Step 3: Create a Consumer Component
Inside the components where you want to access the shared data, use the Consumer component to consume the data from the context.
// ComponentA.js
import React from 'react';
import MyContext from './context';
import ComponentB from './ComponentB';
function ComponentA() {
return (
<div>
<h2>Component A</h2>
<MyContext.Consumer>
{(data) => <p>{data}</p>}
</MyContext.Consumer>
<ComponentB />
</div>
);
}
export default ComponentA;Step 4: Access Shared Data in Nested Components The data from the context is automatically propagated down the component tree, so you can access it in nested components as well.
// ComponentB.js
import React from 'react';
import MyContext from './context';
function ComponentB() {
return (
<div>
<h3>Component B</h3>
<MyContext.Consumer>
{(data) => <p>{data}</p>}
</MyContext.Consumer>
</div>
);
}
export default ComponentB;The Context API allows you to avoid prop drilling, making it easier to manage and share global state between components. Remember that you can use the Context API for more complex state management, but if your application requires more advanced features like state persistence or complex state changes, you might consider using external state management libraries like Redux or MobX.
EXAMPLE
Sure! Here's a code sample demonstrating how to use the Context API in React:
// Step 1: Create the Context
import React, { createContext, useState, useContext } from 'react';
// Create a new context with a default value
const MyContext = createContext();
// Step 2: Create a Provider Component
const MyContextProvider = ({ children }) => {
// Define the state or data you want to share
const [count, setCount] = useState(0);
return (
<MyContext.Provider value={{ count, setCount }}>
{children}
</MyContext.Provider>
);
};
// Step 3: Use the Context in your Components
const DisplayCount = () => {
// Use the useContext hook to access the context value
const { count } = useContext(MyContext);
return <div>Count: {count}</div>;
};
const IncreaseButton = () => {
// Use the useContext hook to access the context value and update the count
const { count, setCount } = useContext(MyContext);
const handleIncrease = () => {
setCount(count + 1);
};
return <button onClick={handleIncrease}>Increase</button>;
};
const DecreaseButton = () => {
// Use the useContext hook to access the context value and update the count
const { count, setCount } = useContext(MyContext);
const handleDecrease = () => {
setCount(count - 1);
};
return <button onClick={handleDecrease}>Decrease</button>;
};
// Step 4: Wrap your App with the Provider Component
const App = () => {
return (
<MyContextProvider>
<DisplayCount />
<IncreaseButton />
<DecreaseButton />
</MyContextProvider>
);
};
export default App;In this example, we create a context using createContext and a Provider component MyContextProvider, which wraps around the components that need to access the shared data. The MyContextProvider provides the state count and the setCount function to update the count to all the components wrapped inside it.
The components DisplayCount, IncreaseButton, and DecreaseButton are consuming the count and setCount values using the useContext hook. When you click the "Increase" or "Decrease" buttons, the count will be updated, and the DisplayCount component will re-render with the updated count.
The Context API allows you to pass data and functions down the component tree without explicitly passing them through props, making it a powerful tool for managing state and sharing data across multiple components in your React application.