Lifting State Up
Sometimes two components need the same data. A product list adds items, and the header shows the cart count. Neither can read the other's state.
The answer: lift the state up to their closest common parent. The parent keeps the state and passes it down as props, together with functions that change it.
This is one of the most important ideas in React. Every piece of data should have exactly one owner - one component whose state holds it. When two siblings need the same data, neither can own it, so the owner moves up to their parent. The parent is then the single source of truth, and the siblings just display or request changes. If you ever find two components holding copies of the same data that get out of sync, lifting state up is usually the fix.
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.24.7/babel.min.js"></script>
<script type="text/babel">
const { useState } = React;
function Header({ count }) {
return <h2>🛒 Cart: {count} items</h2>;
}
function ProductList({ onAdd }) {
const products = ["Pen", "Notebook", "Bag"];
return (
<ul>
{products.map(p => (
<li key={p}>
{p} <button onClick={() => onAdd(p)}>Add</button>
</li>
))}
</ul>
);
}
function App() {
const [cart, setCart] = useState([]); // the shared state lives here
const add = item => setCart(c => [...c, item]);
return (
<div>
<Header count={cart.length} />
<ProductList onAdd={add} />
<p>In cart: {cart.join(", ") || "nothing yet"}</p>
</div>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
</body>
</html>▶ Try it yourselfThe rule of thumb
- State lives in the lowest component that every user of it is inside.
- Data flows down as props.
- Changes flow up through callback props like
onAdd.
setCart(c => [...c, item]), using the current value c. React may group updates together, and this form always uses the latest value.- Shared state lives in the closest common parent.
- Pass data down as props and changes up as callback functions.
- Use the function form of setState when the new value depends on the old one.
