Full-Stack Development · Tutorial 8 of 9
State Management in React: lifting state and context
By the FUTEAC Team · 17 November 2026 · 14 min read · Beginner
In short
State is data a component remembers. When two components need the same data, keep it in their shared parent and pass it down: that is lifting state. When data is needed deep in the tree, context lets any component read it directly. This tutorial builds a small shop with both, and shows the two mistakes that break them.
- State lives in one place, and every component that needs it reads from that place. Two copies of the same data will disagree sooner or later.
- Lifting state means moving
useStateup to the nearest shared parent, then passing the value and the updater down as props. - Context is a pipe past the middle layers. A component reads a value with
useContextwithout the components in between knowing about it. - Context still needs a Provider. Without one, the component silently gets the default value, and nothing errors.
- This tutorial feeds the React from Scratch course (/course/react-from-scratch) and the State Management (/skill/state-management) skill.
Before you start
What is state, and when does it become a problem?
State is data a component remembers between renders. Item 14 gave a counter its own useState, and that worked because only the counter needed the count. The trouble starts when two components need the same piece of data.
Picture a small shop. The header shows "Cart (0 items)". The product list has an "Add to cart" button under each product. If the header keeps its own count and the product list keeps its own list of items, the two will disagree. The header says 0 while the list holds two items, because each component is remembering its own private copy.
Think of it like a shopping list on the fridge. One list, stuck where everyone can see it, and the whole household stays in step. Give each person their own copy and someone buys milk twice while nobody buys bread. Shared data needs one home, not one copy per component. That one home is the job of this tutorial.
The demo for this tutorial is a Mini Shop with three products, a header that shows the cart count, and a theme toggle buried in the footer. It is one file, src/App.jsx, and you will build it in two moves: lift the cart state first, then add context for the theme.
How do you set up the demo app?
Create a Vite React app and start it:
npm create vite@latest my-shop-app -- --template react
cd my-shop-app
npm install
npm run devOpen the address Vite prints, usually http://localhost:5173. The versions installed for this tutorial were Vite 8.3.8 and React 19.3.1. All the work goes in one file, src/App.jsx. Replace its contents step by step as you follow along.
How do you lift state up?
Lifting state means moving the useState call to the nearest component that is a parent of everyone who needs the value. In the Mini Shop, the header needs the cart count and the product list needs to add to the cart, so the state lives in App, their shared parent. App passes the count down to Header and the add function down to ProductList.
Start with the products and the two components that share the cart:
import { useState } from "react";
const products = [
{ id: 1, name: "Notebook", price: 350 },
{ id: 2, name: "Pen set", price: 250 },
{ id: 3, name: "Desk lamp", price: 1800 },
];
function Header({ cartCount }) {
return (
<header>
<h1>Mini Shop</h1>
<p>Cart ({cartCount} items)</p>
</header>
);
}
function ProductList({ onAdd }) {
return (
<ul>
{products.map((product) => (
<li key={product.id}>
{product.name} - Rs {product.price}{" "}
<button onClick={() => onAdd(product)}>Add to cart</button>
</li>
))}
</ul>
);
}Two details to notice. Header receives only the count, not the whole cart, because that is all it needs. And ProductList receives a function, onAdd, not the cart itself: the list does not need to know what is in the cart, only how to add to it. Passing down the smallest piece each component needs keeps the code easy to follow later.
Now add App, which owns the state:
export default function App() {
const [cart, setCart] = useState([]);
function addToCart(product) {
setCart((prevCart) => [...prevCart, product]);
}
return (
<div>
<Header cartCount={cart.length} />
<ProductList onAdd={addToCart} />
</div>
);
}Save the file and click "Add to cart" under Notebook, then under Pen set. The header changes to "Cart (2 items)". The count lives in one place, App, and both components read from it. If you add the same product twice, the count goes to 2 and then 3, because the cart is a list of items, not a list of distinct products. A real shop would group duplicates and show quantities, and that is one of the Try It tasks below.
The wrong turn: two quick clicks, one item in the cart
The addToCart above uses the functional form of the updater, setCart((prevCart) => [...prevCart, product]). Here is why that matters, and this is a mistake we made while testing this tutorial, not a made-up one.
The first version of the function read the cart straight from the component:
function addToCart(product) {
setCart([...cart, product]);
}It looks right, and with slow human clicks it works, because React re-renders between clicks and cart is fresh each time. But when two clicks land in the same tick, before React has re-rendered, both calls read the same cart: the empty array. Each builds a one-item array, the second overwrites the first, and the header shows "Cart (1 items)" after two clicks. We reproduced exactly that in the test render: two clicks, cart count 1.
The fix is the functional updater. setCart((prevCart) => [...prevCart, product]) hands React a function, and React calls it with the latest cart value at the time it applies the update, not the value from the last render. Two quick updates then chain correctly: the second one sees the first one's item. After the fix, the same two-click test shows "Cart (2 items)".
The rule is simple: whenever the new state is built from the old state, pass a function to the setter. It costs nothing and it removes a whole class of bugs that only show up when a user clicks fast.
When is lifting state not enough?
Lifting state works until the component that needs the value sits deep in the tree. Add a theme toggle to the Mini Shop, and put the button in the footer. The footer is a child of App, but the button is a child of the footer, and the theme value also has to reach the wrapper div that carries the theme class. With props alone, App passes the theme to Footer, Footer passes it to ThemeButton, and every layer in between carries a prop it never uses. Add a sidebar and a settings panel and the chain gets longer.
That chain is called prop drilling, and it is the sign you need context. Think of it as the difference between passing a note down a row of people and announcing it over the PA system. The note has to travel through every hand, and anyone can drop it. The announcement reaches the right person directly, and the people in between never touch it.
Context is React's PA system. You create a context, a Provider supplies the value at the top, and any component below it reads the value with useContext, no matter how deep it sits.
How does context work?
Three pieces: createContext makes the context, the Provider supplies the value, and useContext reads it. Add them to the shop. First, the context and the button that reads it:
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext({
theme: "light",
toggleTheme: () => {},
});
function ThemeButton() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<button onClick={toggleTheme}>
Switch to {theme === "light" ? "dark" : "light"} mode (now {theme})
</button>
);
}
function Footer() {
return (
<footer>
<p>Thanks for visiting the Mini Shop.</p>
<ThemeButton />
</footer>
);
}createContext takes a default value, used only when no Provider is above the component. We will come back to that default in the next section, because it is the source of the second wrong turn.
Notice what Footer does not do: it receives no theme prop and passes nothing down. ThemeButton reads the context itself. That is the whole point. The footer stays simple, and the button still gets everything it needs.
Now wire the Provider into App, next to the cart state:
export default function App() {
const [cart, setCart] = useState([]);
const [theme, setTheme] = useState("light");
function addToCart(product) {
setCart((prevCart) => [...prevCart, product]);
}
function toggleTheme() {
setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
}
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
<div className={theme}>
<Header cartCount={cart.length} />
<ProductList onAdd={addToCart} />
<Footer />
</div>
</ThemeContext.Provider>
);
}The Provider wraps everything that needs the theme, and its value is an object holding the theme and the toggle function. Save the file and click the theme button in the footer. The label changes to "Switch to light mode (now dark)", and the wrapper div changes its class from light to dark. In our test render the button and the class both changed on one click, which is how we confirmed the Provider was wired up. The class does not change any colours by itself, since the demo has no .dark styles yet: that is a styling job, and adding a dark rule is a Try It task below.
One opinion, since this choice comes up in every React project: we use context for theme, login state, and other app-wide values that many components read but few change. We do not use it for everything, because a context update re-renders every component that reads it, and a cart that changes on every click does not belong in the same pipe as a theme that changes twice a session. Lift the fast-changing data, put the slow, widely read data in context.
Lifting state or context: how do you choose?
Use this rule. If the components that share the data are close together, parent and children, or siblings, lift the state to their shared parent. It is plain props, it is easy to trace, and it is the first tool to reach for. If the data is needed by components in different branches, or several layers down, and passing props means threading the same value through components that never use it, use context.
A few more cases help. Form input state stays local to the form until another component needs it. A logged-in user belongs in context, because the header, the route guard from item 54, and the profile page all read it. A shopping cart usually stays lifted in the shop page, or moves to a store library later, which is beyond this tutorial. When in doubt, lift first. You can move lifted state into context later in one step, and the components that read it barely change.
Try it yourself
1. Group duplicate products in the cart: change the cart to hold { product, quantity } pairs, and show the quantity next to each product name. Check the header count still matches the total number of items. 2. Add a dark theme rule to src/index.css: a .dark class that gives the page a dark background and light text. Click the theme button and check the colours change. (index.css is the stylesheet the starter already loads; App.css is not imported by this demo.) 3. Move the theme state into its own file, src/ThemeContext.jsx, that exports both the context and a ThemeProvider component. Import it in App.jsx and check the app still works. 4. Add a "Clear cart" button in the header that empties the cart. It needs the setter, so think about which prop App has to pass down.
Common mistakes
- Building new state from old state without the functional updater. Two quick updates read the same stale value and one overwrites the other. Pass a function to the setter whenever the new state depends on the old one.
- Forgetting the Provider. The component renders with the context default, the button does nothing, and nothing errors. Wrap every reader in the Provider.
- Putting everything in context. A context update re-renders every reader, so fast-changing data like a cart makes the whole tree re-render on every click. Lift fast-changing state, reserve context for slow, widely read values.
- Passing a fresh object literal as the Provider value without thinking.
value={{ theme, toggleTheme }}creates a new object on every render, which re-renders every reader even when the theme did not change. For a small app it does not matter, and this tutorial keeps it simple. In a bigger app, wrap the value inuseMemo. - Changing state directly instead of replacing it.
cart.push(product)mutates the array in place, and React sees the same array reference and skips the re-render. Always build a new array, as[...prevCart, product]does.
Frequently asked questions
Do I need a state library like Redux or Zustand for this?
No, not yet. Lifting state plus context covers most small and medium apps. Reach for a library when state updates get tangled across many unrelated components, or when you need features like time-travel debugging. Learn the React built-ins first, so you recognise the problem a library is solving.
Can a component read more than one context?
Yes. Call useContext once per context, and nest the Providers in App. A theme context and a login context can sit side by side, each with its own Provider.
Why does the context default value matter if I always use a Provider?
It matters exactly when you forget the Provider, which is the wrong turn above. A default with a no-op function fails silently. Some teams set the default to null and throw a clear error when a component reads it outside a Provider, so the mistake shows up at once instead of hiding.
Is context the same as global state?
Close, but not identical. Context is React's built-in way to share a value down the tree without props. A state library also shares values, and adds its own update rules, devtools, and performance controls. Context is the simplest version of the idea, and it is enough for the apps in this series.
Where does the login state from item 54 live?
In context, in the real app. Item 54 ended with a route guard that checks whether the user is logged in. That check reads a login context, the same shape as the theme context here: a Provider near the top of the app, and useContext in the guard. The login pattern itself is in Authentication Basics (item 32).
Follow the Full-Stack Developer Roadmap
Build complete web applications, frontend, backend APIs, databases and deployment. Free, step by step, at your pace.
View the Roadmap