State and events · Lesson 10 of 21
Lifting state up
When two components need the same data: a single source of truth.
9 minutes2 games
If two sibling components need the same state (like a course list and a cart counter), don't give each its own copy; they'll drift apart. Lift the state to their closest common parent, and pass the value down as props along with a function to change it.
React
const COURSES = [
{ id: 2, title: "JavaScript", price: 450 },
{ id: 3, title: "Python", price: 400 },
{ id: 5, title: "React", price: 600 },
]
function CourseList({ cart, onToggle }) {
return (
<ul>
{COURSES.map((c) => (
<li key={c.id}>
{c.title} ({c.price}){" "}
<button onClick={() => onToggle(c.id)}>{cart.includes(c.id) ? "Remove" : "Add"}</button>
</li>
))}
</ul>
)
}
function CartSummary({ cart }) {
const total = COURSES.filter((c) => cart.includes(c.id)).reduce((sum, c) => sum + c.price, 0)
return <p>🛒 {cart.length} courses · {total} EGP</p>
}
function App() {
const [cart, setCart] = useState([])
const toggle = (id) => setCart((c) => (c.includes(id) ? c.filter((x) => x !== id) : [...c, id]))
return (
<>
<CartSummary cart={cart} />
<CourseList cart={cart} onToggle={toggle} />
</>
)
}- App: cart state + toggle()
- CartSummary ← cart (props down)
- CourseList ← cart, onToggle
- button → onToggle(id) (event up)
Data flows down as props; events flow up as callbacks.
Order the lines
Order the code: the parent owns the state and passes it down with a setter.
- Click the lines in the right order
Exercise
A Stepper component shows only - and + buttons, while the parent App holds the number and shows Seats: N (starting at 1). The checker presses + twice and - once.
The page should show:
Seats: 2 - +
React
function Stepper({ onChange }) {
return (
<div>
<button className="minus">-</button>
<button className="plus">+</button>
</div>
)
}
function App() {
return (
<div>
<p>Seats: 1</p>
<Stepper />
</div>
)
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.