ReactEasy

What is 'lifting state up'?

Lifting state up means moving state from child components to their closest common parent, so that several children can share and stay in sync with the same data. The parent holds the state and passes the value down as props, plus callbacks the children call to change it.

When to lift

  • Two siblings need the same data (a filter input and the list it filters).
  • A child's value must be known by the parent (form fields used on submit).
  • Components must stay in sync (accordion panels where only one can be open).

How

  1. Remove the state from the children.
  2. Add it to the nearest common parent.
  3. Pass the value down as a prop.
  4. Pass a callback such as onChange so children can request updates.

The children become controlled components: their output is fully determined by props.

Single source of truth

Each piece of state should live in exactly one place. Duplicating it in several components leads to inconsistent UI.

When lifting gets painful

If you lift too high, many intermediate components just pass props through (prop drilling). Options: composition (pass components as children), context for widely needed values, or a store (Zustand, Redux) for app-wide state. Keep state as low as possible, as high as necessary.

Code example

tsx
1import { useState } from "react";
2
3function SearchBox({ query, onQueryChange }: { query: string; onQueryChange: (q: string) => void }) {
4 return <input value={query} onChange={(e) => onQueryChange(e.target.value)} placeholder="Filter" />;
5}
6
7function FruitList({ query }: { query: string }) {
8 const fruits = ["Apple", "Banana", "Cherry", "Mango"];
9 const visible = fruits.filter((f) => f.toLowerCase().includes(query.toLowerCase()));
10 return <ul>{visible.map((f) => <li key={f}>{f}</li>)}</ul>;
11}
12
13// State lifted to the common parent: both children stay in sync
14export function FruitFilter() {
15 const [query, setQuery] = useState("");
16 return (
17 <section>
18 <SearchBox query={query} onQueryChange={setQuery} />
19 <FruitList query={query} />
20 </section>
21 );
22}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app