Quiz
Warm-up. From unit 3, props flow parent → child and are read-only. From unit 4, state is owned by one component. So how can a SearchBox component and a ResultsList component, siblings, share the same query text?
Lifting state up
The rule: state lives in the closest common parent of every component that needs it. The parent owns the value, children get it as props, and children that need to change it get a function prop.
function SearchPage({ products }) { const [query, setQuery] = useState(""); return ( <> <SearchBox query={query} onQueryChange={setQuery} /> <ResultsList products={products} query={query} /> </> ); } function SearchBox({ query, onQueryChange }) { return ( <input value={query} onChange={e => onQueryChange(e.target.value)} /> ); } function ResultsList({ products, query }) { const shown = products.filter(p => p.name.toLowerCase().includes(query.toLowerCase()) ); return <ul>{shown.map(p => <li key={p.id}>{p.name}</li>)}</ul>; }
Typing in the box calls onQueryChange, which is the parent's setQuery. The parent re-renders, and BOTH children receive the new query. One source of truth, two consumers, the controlled-input idea from lesson 6-1 applied between components.
Code exercise · javascript
Your turn, the SearchPage as runnable JavaScript. The parent owns query, searchBox and resultsList both receive it as an argument, and onQueryChange plays the function prop that carries changes up before re-rendering. Complete resultsList: filter products whose lowercased name includes the lowercased query, then map to <li> strings.
Quiz
A CartIcon in the header and a CartPage in the main area both show the number of cart items. Following the lifting rule, where does the cart state live?
Problem
A child component needs to add an item to a list that lives in its parent's state. Props are read-only. What does the parent pass to the child so it can request the change?