Course outline · 0% complete

0/28 lessons0%

Course overview →

Lifting state up

lesson 8-1 · ~14 min · 22/28

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.

SearchPagestate: querySearchBoxquery, onQueryChangeResultsListproducts, queryprops flow downprops flow downevents flow up: onQueryChange(text) → setQuery
Lifted state. The parent owns query, both children receive it as props (solid gold dots moving down), and SearchBox reports changes upward by calling the function prop (hollow dot moving up).

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?