Module 33: State and Events

Lesson 5 of 5 · 15–25 minutes

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

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} />
    </>
  );
}

🖱️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.

← PreviousControlled inputs
ProLearners Assist