Part 03 / Topic 6 of 7
Lifting state up: sharing state between siblings
Every example so far has one component owning its own state. examples/05_lifting_state_up.jsx asks a different question: what happens when two sibling components both need the same value? RestaurantSearchPanelBroken tries to answer it by giving each sibling its own, separate useState:
// examples/05_lifting_state_up.jsx (broken, trimmed)
function SearchBoxBroken() {
const [query, setQuery] = useState("");
return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}
function ResultsSummaryBroken() {
const [query] = useState(""); // nothing outside this component ever sets it
return <p>{query ? `Showing results for "${query}"` : "Showing all restaurants"}</p>;
}
Typing "Swiggy" into the search box really does update that box's own query - but ResultsSummaryBroken's own, separate query never moves, because the two components never shared anything beyond a variable name that happens to match. Rendering both inside RestaurantSearchPanelBroken and typing into the box really leaves the summary stuck (examples/05_lifting_state_up.test.jsx):
type "Swiggy" into the search box
→ the box itself shows "Swiggy"
the summary still reads "Showing all restaurants"
Lifting state up means moving the state to the closest common parent of every component that needs it, instead of duplicating it. RestaurantSearchPanelFixed owns the one query value and hands the value down to one child, the setter down to the other:
// examples/05_lifting_state_up.jsx (fixed, trimmed)
export function RestaurantSearchPanelFixed() {
const [query, setQuery] = useState("");
return (
<div>
<SearchBoxFixed query={query} onQueryChange={setQuery} />
<ResultsSummaryFixed query={query} />
</div>
);
}
Neither child has its own useState for query anymore - SearchBoxFixed reads query as a prop and calls onQueryChange (which is just setQuery, passed down under a more descriptive name) on every keystroke; ResultsSummaryFixed only ever reads query as a prop. Typing "Swiggy" into RestaurantSearchPanelFixed's search box really does update the sibling summary this time (examples/05_lifting_state_up.test.jsx):
type "Swiggy" into the search box
→ the box itself shows "Swiggy"
the summary now reads 'Showing results for "Swiggy"'
Nothing about useState changed between the broken and fixed versions - only where it is called did. This is the same move Stage 1's Menu Browser project will eventually need between its search box and its filtered list, and the same move Part 6's context lesson exists to avoid repeating by hand once sharing state gets several levels deeper than one parent and two children.
Done here? The practice set for Part 3 — including the solutions — is on the part page.