WEB II State Management Basics Lesson008
WEB II State Management Basics Lesson008
Context API
State management using React's Context API involves creating a context to hold state, providing
the context to components that need access to the state, and consuming the state within those
components. This approach avoids prop drilling, where state is passed down through multiple
levels of components.
Create a context:
Using React.createContext(), a context object is created. This object includes a provider and a
consumer.
A provider component wraps the part of the component tree that needs access to the state. The
provider's value prop is used to pass the state and any update functions.
Components within the provider can access the state using useContext hook
or Context.Consumer. The useContext hook is generally preferred for its simplicity.
It can be used together with the useState Hook to share state between deeply nested
components more easily than with useState alone.
The Problem
State should be held by the highest parent component in the stack that requires access to the
state.
To illustrate, we have many nested components. The component at the top and bottom of the
stack need access to the state.
To do this without Context, we will need to pass the state as "props" through each nested
component. This is called "prop drilling".
Create Context
To create context, you must Import createContext and initialize it:
Next we'll use the Context Provider to wrap the tree of components that need the state
Context.
Context Provider
Wrap child components in the Context Provider and supply the state value.
function Component1() {
return (
<UserContext.Provider value={user}>
<h1>{`Hello ${user}!`}</h1>
</UserContext.Provider>
);
Now, all components in this tree will have access to the user Context.
return (
<>
<h1>Component 5</h1>
</>
);
Full Example
src/context/UserContext.js
src/components/Component1.jsx
function Component1() {
return (
<UserContext.Provider value={user}>
<h1>{`Hello ${user}!`}</h1>
<Component2 />
</UserContext.Provider>
);
src/components/Component2.jsx
function Component2() {
return (
<>
<h1>Component 2</h1>
<Component3 />
</>
);
src/components/Component3.jsx
function Component3() {
return (
<>
<h1>Component 3</h1>
<Component4 />
</>
);
src/components/Component4.jsx
function Component4() {
return (
<>
<h1>Component 4</h1>
<Component5 />
</>
);
src/components/Component5.jsx
function Component5() {
const user = useContext(UserContext);
return (
<>
<h1>Component 5</h1>
</>
);
src/App.jsx
function App() {
return (
<div className="App">
<Component1 />
</div>
);
src/main.jsx
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
1. Context API:
o Creates a global state that can be accessed by any component without prop
drilling
o Provider component wraps the part of the app that needs access to the context
o The intermediate components (2-4) don't need to know about the user state