Context provides a way to pass data through the component tree without having to pass props down manually at every level. It’s essentially a global state management solution that allows you to share data between components without having to explicitly pass the data through props at every level of the component tree.
A step-by-step guide to create a context
Create a Context
To create a React context use the React.createContext() function. It creates a context object. The only argument to createContext is the default value. If you don’t have a default value, specify null.
app-context.js
import { createContext } from "react";
export const AppContext = createContext(null);
Provide a Context
Wrap the part of your component tree that needs access to the context with a <Context.Provider> component. This provider accepts the value attribute (props) with data that you want to share with components that are descendants of this provider. Replace <Context.Provider> with the name you assigned to your context. In this case, the context variable is named AppContext, so you would replace <Context.Provider> with <AppContext.Provider>.
App.js
import "./App.css";
import { AppContext } from "./context/app-context";
import { useState } from "react";
function App() {
const [appData, setAppData] = useState({ data: {} });
return (
<AppContext.Provider value={{ appData, setAppData }}>
<div className="App">
...
</div>
</AppContext.Provider>
);
}
export default App;
useState within a context provider allows you to manage the state that you want to share across your application components. While context itself provides a way to pass down data through the component tree without having to pass props manually at every level, using useState within a provider allows you to manage the state of that context data. Any components consuming AppContext will have access to appData and setAppData, allowing them to read and update the state as needed. useState lets you add context data to your application.
Consume a Context
Components that want to access the context data can do it using the useContext. useContext is a React hook that allows components to consume context values.
Component.js
import { useContext } from "react";
import { AppContext } from "../context/app-context";
export default function Component() {
const { appData, setAppData } = useContext(AppContext);
function changeContext() {
setAppData((prev) => ({
data: {...prev.data, newProp: true},
}));
}
console.log(appData);
return (
<div>
<div>{JSON.stringify(appData.data)}</div>
<button onClick={changeContext}>Change context</button>
</div>
);
}
useContext(AppContext) fetches the current context data. It returns the current context value for the specified context, which in this instance is AppContext.