Skip to content

Lesson 9 of 37State

Lifting State Up

Share state between components by moving it to their closest common parent and passing it down as props.

18 min read0/7 questions

Sooner or later two components need the same data: a search box and the results list, a cart icon and the product page, two accordion panels where opening one closes the other. Because state is private to each component, they cannot reach into each other. The fix, lifting state up, is the single most important pattern for structuring React apps, and interviewers use it to judge whether you can design components, not just write them.

The problem: siblings cannot share

Here is an FAQ where each panel keeps its own isOpen state. The requirement is "only one answer open at a time". Try opening both.

React
import { useState } from "react"; function Panel({ title, children }: { title: string; children: string }) { const [isOpen, setIsOpen] = useState(false); return ( <section style={{ borderBottom: "1px solid #ddd", padding: "6px 0" }}> <button onClick={() => setIsOpen(!isOpen)}>{title}</button> {isOpen && <p>{children}</p>} </section> );} export default function App() { return ( <div> <Panel title="Shipping">Orders ship within 2 business days.</Panel> <Panel title="Returns">Return anything within 30 days.</Panel> </div> );}

Both open, and there is no way to fix it inside Panel: the first panel cannot see or change the second panel's state.

The fix in three steps

To coordinate siblings, move the state to their closest common parent and pass it down.

  1. Remove the state from the children.
  2. Pass what they need as props from the parent: here, isOpen.
  3. Add an event prop so children can ask the parent to change it: here, onShow.
React
import { useState } from "react"; type PanelProps = { title: string; children: string; isOpen: boolean; onShow: () => void }; function Panel({ title, children, isOpen, onShow }: PanelProps) { return ( <section style={{ borderBottom: "1px solid #ddd", padding: "6px 0" }}> <button onClick={onShow}>{title}</button> {isOpen && <p>{children}</p>} </section> );} export default function App() { const [openIndex, setOpenIndex] = useState(0); return ( <div> <Panel title="Shipping" isOpen={openIndex === 0} onShow={() => setOpenIndex(0)}> Orders ship within 2 business days. </Panel> <Panel title="Returns" isOpen={openIndex === 1} onShow={() => setOpenIndex(1)}> Return anything within 30 days. </Panel> </div> );}

Now App holds one number, openIndex, and each panel's isOpen is derived from it. Two panels can never both be open, because the data cannot express that.

Put it in order5 steps

Order the steps to lift state from two siblings into their parent.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Where state lives, what re-renders

When the state changes, React re-renders the component that owns it and, by default, every component below it. Lifting state therefore has a cost: the higher you put it, the more re-renders. That is usually fine (rendering is fast), but it is a reason not to lift state higher than needed.

A shop page: who owns what
AppCartBadgereads cartCountHeaderSearchBoxprops: query, onQueryChangeProductCardProductCardResultsprops: querySearchPagestate: queryFooterroot

SearchBox and Results both need query. Their closest common parent is SearchPage, so the state lives there (pink).

1/4
Quick check
A Sidebar shows the selected folder, and MessageList shows that folder's messages. Both are children of Mailbox, which is a child of App. Where should selectedFolder live?
Need a nudge? A hint rules out a wrong answer.

Controlled and uncontrolled components

After lifting, Panel has no state of its own. Its behaviour is fully decided by props. A component like that is called controlled: the parent controls it. The first version, with its own isOpen, was uncontrolled: the parent could not influence it.

UncontrolledControlled
Who owns the stateThe component itselfIts parent, via props
Parent can read or change itNoYes
SetupLess code, drop it inParent must pass value and onChange
Example<input defaultValue="hi" /><input value={text} onChange={...} />

You will see the same words with form inputs in the next lesson. The idea is identical: is the value driven by React state through props, or kept internally?

A single source of truth

For each piece of data, exactly one component should own it as state. Everything else receives it as props or computes it. This is the single source of truth principle.

A common mistake is copying a prop into state:

function Greeting({ name }: { name: string }) {
  // Bug: only uses `name` on the first render. If the parent's name changes, this stays stale.
  const [displayName, setDisplayName] = useState(name);
  return <h2>Hello, {displayName}</h2>;
}
 
function GreetingFixed({ name }: { name: string }) {
  return <h2>Hello, {name}</h2>; // just use the prop
}
Quick check
The parent renders <Greeting name={name} /> (the buggy version) with name set to Ada, then later changes name to Sam. What does the heading show?
Need a nudge? A hint rules out a wrong answer.

Here is the search example wired properly. query lives in the parent; the input is controlled; the results are derived during render, never stored.

React
import { useState } from "react"; const PRODUCTS = ["Keyboard", "Mouse", "Monitor", "Microphone", "Webcam", "Desk lamp"]; function SearchBox({ query, onQueryChange }: { query: string; onQueryChange: (q: string) => void }) { return <input aria-label="Search" placeholder="Search..." value={query} onChange={(e) => onQueryChange(e.target.value)} />;} function Results({ query }: { query: string }) { const hits = PRODUCTS.filter((p) => p.toLowerCase().includes(query.toLowerCase())); return ( <ul> {hits.map((p) => ( <li key={p}>{p}</li> ))} </ul> );} export default function App() { const [query, setQuery] = useState(""); return ( <div> <SearchBox query={query} onQueryChange={setQuery} /> <p>Searching for: {query || "everything"}</p> <Results query={query} /> </div> );}

Deriving instead of syncing state

Once state lives in the right place, the next mistake is storing things you could compute. Ask of every piece of state: can I calculate this from props or other state? If yes, it is not state. Calculate it during render.

You will meet useEffect later in the course. A very common misuse of it is to "keep two pieces of state in sync":

// Avoid: hits is a copy of something you can compute
const [query, setQuery] = useState("");
const [hits, setHits] = useState(PRODUCTS);
useEffect(() => {
  setHits(PRODUCTS.filter((p) => p.includes(query)));
}, [query]);
 
// Better: derive it. No extra state, no extra render, never out of date
const [query, setQuery] = useState("");
const hits = PRODUCTS.filter((p) => p.includes(query));

The effect version renders twice for every keystroke: once with the new query and the old hits, then again after the effect runs. For a moment the screen is wrong, and on a slow device users see it. If the calculation is genuinely expensive, wrap it in useMemo (the performance lesson covers when that helps). It is still derived; you are just caching it.

The most valuable form of this rule: store ids, not copies. Here is a recipe planner. Select Pasta, then click "+1 serving" on Pasta in the list. Do it in both versions.

React
import { useState } from "react"; type Recipe = { id: number; title: string; servings: number };const RECIPES: Recipe[] = [ { id: 1, title: "Pasta", servings: 2 }, { id: 2, title: "Curry", servings: 4 },]; type ListProps = { recipes: Recipe[]; onSelect: (r: Recipe) => void; onMore: (id: number) => void }; function RecipeList({ recipes, onSelect, onMore }: ListProps) { return ( <ul style={{ paddingLeft: 18 }}> {recipes.map((r) => ( <li key={r.id}> <button onClick={() => onSelect(r)}>{r.title}</button> {r.servings} servings{" "} <button onClick={() => onMore(r.id)}>+1 serving</button> </li> ))} </ul> );} const addServing = (list: Recipe[], id: number) => list.map((r) => (r.id === id ? { ...r, servings: r.servings + 1 } : r)); function CopyPlanner() { const [recipes, setRecipes] = useState(RECIPES); const [selected, setSelected] = useState<Recipe>(RECIPES[0]); // a copy of an item return ( <section> <strong>Stores a copy</strong> <RecipeList recipes={recipes} onSelect={setSelected} onMore={(id) => setRecipes(addServing(recipes, id))} /> <p>Cooking {selected.title} for {selected.servings}</p> </section> );} function IdPlanner() { const [recipes, setRecipes] = useState(RECIPES); const [selectedId, setSelectedId] = useState(RECIPES[0].id); // only the id const selected = recipes.find((r) => r.id === selectedId)!; // derived return ( <section> <strong>Stores the id</strong> <RecipeList recipes={recipes} onSelect={(r) => setSelectedId(r.id)} onMore={(id) => setRecipes(addServing(recipes, id))} /> <p>Cooking {selected.title} for {selected.servings}</p> </section> );} export default function App() { return ( <div style={{ display: "grid", gap: 12 }}> <CopyPlanner /> <IdPlanner /> </div> );}

In the first planner the list says 3 servings and the detail line still says 2. selected is a second copy of the Pasta object, and updating the list made a new Pasta object that the copy knows nothing about. Two sources of truth, and they drifted. Storing only selectedId and looking the item up during render means there is one Pasta, so it can never be stale. The same applies to "the selected rows" (store a set of ids), "the item being edited" and "the current user's cart line".

Quick check
A table of users has a detail panel. Someone renames the selected user in the table and the panel still shows the old name. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.

Resetting state with key

Earlier you saw why copying a prop into state is a bug: useState(name) only reads name on the first render. Sometimes, though, a copy is exactly what you want. An edit form needs a draft that starts from the saved contact, changes as you type, and only touches the real data when you press Save. That draft is state, and its starting value comes from a prop.

The problem appears when the prop changes to a different contact. The form component stays mounted, so its draft still holds the previous contact's name. The fix is not to sync it with an effect. It is to tell React that a different contact means a different form, with a key:

React
import { useState } from "react"; type Contact = { id: number; name: string }; function EditContact({ contact, onSave }: { contact: Contact; onSave: (c: Contact) => void }) { const [draft, setDraft] = useState(contact.name); // starts from the prop, on mount only return ( <div style={{ display: "flex", gap: 6 }}> <input aria-label="Name" value={draft} onChange={(e) => setDraft(e.target.value)} /> <button onClick={() => onSave({ ...contact, name: draft })}>Save</button> </div> );} export default function App() { const [contacts, setContacts] = useState<Contact[]>([ { id: 1, name: "Ada" }, { id: 2, name: "Sam" }, ]); const [selectedId, setSelectedId] = useState(1); const selected = contacts.find((c) => c.id === selectedId)!; return ( <div style={{ display: "grid", gap: 8, maxWidth: 320 }}> <div style={{ display: "flex", gap: 6 }}> {contacts.map((c) => ( <button key={c.id} onClick={() => setSelectedId(c.id)} style={{ fontWeight: c.id === selectedId ? 700 : 400 }}> {c.name} </button> ))} </div> <EditContact key={selected.id} contact={selected} onSave={(c) => setContacts(contacts.map((x) => (x.id === c.id ? c : x)))} /> </div> );}

Edit Ada's name without saving, then click Sam: the field shows Sam, because key={selected.id} gave Sam his own fresh EditContact. Remove the key in your head and the field would keep showing your half-typed Ada draft while the Save button wrote it onto Sam.

You have four options when state must follow a prop, in rough order of preference:

  1. Do not store it. If the component does not need its own draft, read the prop directly.
  2. Reset with a key, as above, when a new value of the prop means "start over".
  3. Lift the draft up and make the form controlled, when the parent needs to know about it. An "unsaved changes" warning on navigation is a good reason.
  4. Adjust during render: keep the previous prop in state and, if it changed, call the setter during render. React supports this, but it is hard to read, so use it only when you must keep part of the state, such as resetting a selection while keeping a scroll position.

What you should not do is reset state in an effect. The component first renders with the stale draft, the effect fires, and it renders again, so users briefly see the wrong data, and every extra effect is one more thing to keep correct.

Quick check
A CommentBox keeps its text in useState and is rendered as <CommentBox postId={post.id} />. Switching posts keeps the half-written comment from the previous post. What is the simplest correct fix?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/4 matched

Match each situation to the right move.

Choose an item, then its match on the other side.

When lifting goes too far

Lifting is the right first move, but apply it over and over and you get a familiar mess: one component near the top owns twenty pieces of state, and props travel through four layers that never use them just to reach the one that does. That is prop drilling. Every layer in the middle has to change when the data changes shape, and every keystroke re-renders everything under the owner.

The fix is not always "lift higher" or "add a library". Work up this ladder and stop at the first step that solves the problem.

Where should this state live?
  1. Local stateused by one component: keep it there
  2. Closest common parentshared by a few nearby components
  3. Compositionpass JSX through layers instead of data
  4. Contextread at many depths, changes rarely
  5. External storeapp-wide, changes often, many readers
  6. URL or server cachenot really client state at all

Colocate first. State that only one component uses should live in it. Moving state back down is as useful as lifting it up, and it shrinks re-renders.

1/6

Composition is the step most developers skip. Here App owns user, but only UserMenu, three levels down, needs it:

// Drilling: Layout and Sidebar accept `user` only to pass it on
<Layout user={user} />
function Layout({ user }) { return <Sidebar user={user} />; }
function Sidebar({ user }) { return <nav><UserMenu user={user} /></nav>; }
 
// Composition: App builds UserMenu itself; the middle layers just place it
<Layout sidebar={<Sidebar menu={<UserMenu user={user} />} />} />
function Layout({ sidebar }) { return <div className="layout">{sidebar}</div>; }
function Sidebar({ menu }) { return <nav>{menu}</nav>; }

Layout and Sidebar no longer know a user exists. Add a field to the user and only App and UserMenu change. This is the slots idea from the components lesson, applied to data flow.

Signs you have lifted too far: a prop name repeated in four files in a row, a top-level component with a dozen useState calls for unrelated features, or a profiler showing the whole page re-rendering on each keystroke in one input. The context lesson is next on the ladder, and the state management at scale lesson covers stores, URL state and server caches in depth.

Match the pairs0/5 matched

Match each piece of state to where it should live.

Choose an item, then its match on the other side.
ChallengeMedium

One-at-a-time accordion

Each Panel keeps its own isOpen state, so several can be open at once. Lift the state up into App so that at most one panel is open.

  • All panels start closed.
  • Clicking a panel's title button opens it and closes any other.
  • Clicking the title of the panel that is already open closes it.
  • An open panel shows its text in a <p className="answer">.

Panel should receive isOpen and an onToggle callback as props instead of owning state.

React
import { useState } from "react"; type PanelProps = { title: string; children: string }; function Panel({ title, children }: PanelProps) { const [isOpen, setIsOpen] = useState(false); return ( <section> <button onClick={() => setIsOpen(!isOpen)}>{title}</button> {isOpen && <p className="answer">{children}</p>} </section> );} export default function App() { return ( <div> <Panel title="Shipping">Orders ship within 2 business days.</Panel> <Panel title="Returns">Return anything within 30 days.</Panel> <Panel title="Warranty">Every product has a 1 year warranty.</Panel> </div> );}
ChallengeMedium

Synced temperature inputs

Two inputs, Celsius and Fahrenheit, should always agree. Typing in either one updates the other.

  • Both are <input type="text"> with aria-label="Celsius" and aria-label="Fahrenheit".
  • F = C × 9 / 5 + 32 and C = (F − 32) × 5 / 9.
  • Round the converted value to at most one decimal place and show it without trailing zeros (212, not 212.0; 37.8, not 37.77). String(Math.round(x * 10) / 10) does this.
  • If the typed text is empty or not a number, the other input is empty.

Hint: store one piece of state, the text the user typed and which scale it was in, and derive the other input during render.

React
import { useState } from "react"; function TemperatureInput({ label }: { label: string }) { // Each input has its own state, so they cannot stay in sync. const [value, setValue] = useState(""); return ( <label style={{ display: "block" }}> {label}:{" "} <input type="text" aria-label={label} value={value} onChange={(e) => setValue(e.target.value)} /> </label> );} export default function App() { return ( <div> <TemperatureInput label="Celsius" /> <TemperatureInput label="Fahrenheit" /> </div> );}
Key terms
lifting state up
Moving state to the closest common parent of the components that need it, then passing it down as props.
controlled component
A component whose important values come from props, so its parent controls it.
uncontrolled component
A component that keeps its own internal state that the parent cannot drive.
single source of truth
Each piece of data is owned as state by exactly one component; everything else reads or derives it.
derived state
A value computed during render from props or state, instead of being stored separately.
prop drilling
Passing a prop through several components that do not use it, only to reach one that does.
colocation
Keeping state in the component that uses it, as low in the tree as possible.
key reset
Changing a component's key so React mounts a fresh instance with fresh state.