Two components, one truth
A product list adds items; a header shows the cart count. They need the *same* data. The React way: lift the state up to their common parent, pass the value down as props, and pass functions down so children can ask for changes.
Data down, events up
import { useState } from "react";
function Header({ count }) {
return <h2>🛒 {count} in cart</h2>;
}
function Product({ name, onAdd }) {
return (
<p>
{name} <button onClick={onAdd}>Add</button>
</p>
);
}
export default function Shop() {
const [cart, setCart] = useState([]);
const add = (name) => setCart((c) => [...c, name]);
return (
<div>
<Header count={cart.length} />
<Product name="Momo" onAdd={() => add("Momo")} />
<Product name="Lassi" onAdd={() => add("Lassi")} />
</div>
);
}- Keep state as low as possible, but as high as necessary.
- Never copy the same data into two components' state — they'll drift apart.
- Name callback props onSomething; name the handlers handleSomething.