Lifting state up
🏠The everyday picture
Two shop assistants each keep their own notebook of stock, and soon they disagree. The fix is one shared stock book kept by the manager, which both read from and report changes to.
📘What it really is
- When two components need the same state, move it up to their closest common parent, and pass it down as props, along with functions to change it:
function Dashboard() {
const [enquiries, setEnquiries] = useState(sampleEnquiries);
const closeEnquiry = (id: string) =>
setEnquiries(list => list.map(e => e.id === id ? { ...e, status: "closed" } : e));
return (
<>
<Summary enquiries={enquiries} />
<EnquiryList enquiries={enquiries} onClose={closeEnquiry} />
</>
);
}
-
Data flows down through props; changes flow up through callback props. This one-way data flow makes it easy to find where any value comes from.
-
Keep state as low as possible (in the component that uses it) but as high as necessary (where everyone who needs it can reach it).
-
When state must be shared by many distant components, passing props through many levels gets awkward. Module 37 covers Context and other tools for that.
🖱️Try it
Create a Summary component showing counts of new, in-progress and closed enquiries. Place it above the lists.
Make sure it updates immediately when an enquiry is marked closed, because both read the same state from
Dashboard.
✅Quick check
Two sibling components need the same data. Where should the state live?
Show the answer
In their closest common parent, passed down as props.
How does a child component change state that lives in its parent?
Show the answer
By calling a function the parent passed down as a prop.
