React / 60
Lifting state up: one open section at a time
When two components need the same changing data, move the state to their closest common parent and pass it down as props, with a function to change it.
Try the problem first
Open two sections
Try itWith state in each section, open two and they both stay open. Switch to "lifted", and the parent's single openIndex makes it impossible to have two open.
What moves where
Before
each item owns its own state
Menu
Starters
isOpen = true
Mains
isOpen = true
Desserts
isOpen = false
After
the parent owns one value
Menu
openIndex = 1Starters
isOpen = {false}
Mains
isOpen = {true}
Desserts
isOpen = {false}
Lift it in three steps
Remove state from the child
MenuSectionstops callinguseState. It readsisOpenandonTogglefrom props instead. It's now controlled.Add state to the common parent
Menukeeps oneopenIndex.nullmeans everything is closed.Pass the value and a way to change it down
Each section getsisOpen={openIndex === i}andonToggle, which calls the parent's setter.
import { useState } from "react";
const sections = [
{ title: "Starters", items: "Paneer tikka, Gobi 65" },
{ title: "Mains", items: "Masala dosa, Veg biryani" },
{ title: "Desserts", items: "Gulab jamun, Payasam" },
];
function MenuSection({ title, items, isOpen, onToggle }) {
return (
<section>
<button onClick={onToggle} aria-expanded={isOpen}>
{title} {isOpen ? "−" : "+"}
</button>
{isOpen && <p>{items}</p>}
</section>
);
}
export default function Menu() {
const [openIndex, setOpenIndex] = useState(null);
return sections.map((s, i) => (
<MenuSection
key={s.title}
{...s}
isOpen={openIndex === i}
onToggle={() => setOpenIndex(openIndex === i ? null : i)}
/>
));
}Clicking the open section again sets openIndex back to null, so it closes.
Data down, events up
This is the core pattern of React apps:
- Data flows down as props: the parent tells each child
isOpen. - Events flow up through callback props: the child calls
onToggle(), and the parent decides what that means.
The parent is now the single source of truth. There's exactly one place that says which section is open, so the screen can't disagree with itself.
How far up?
Lift to the closest common parent of the components that need the state, and no higher. State that lives too high makes more of the app re-render on every change, and the props have further to travel. When "closest common parent" ends up being many levels away, you hit the next topic's problem: prop drilling.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
