Lesson 9 of 97:27 video

React lifting state up

A seat page says zero tickets while three seats are still picked, because its state lives in two places. See the answer in the first 30 seconds: when two components need the same state, it goes in the closest component above both. Then lifting state up step by step, a total that is one click behind (and why you calculate it instead of storing it), a summary that copies its props into state and stops updating, and the question at the end: should every piece of state go in the top component? It ends with the answer to "where should state live?" as an interviewer would ask it.

In this lesson

  1. 0:00 Three seats, zero tickets
  2. 1:01 One fact, two copies
  3. 2:14 Lifting state up
  4. 3:24 The total
  5. 4:37 A list in the summary
  6. 5:35 Everything in App?
  7. 7:01 Next: useEffect

Here’s a cinema’s page called Pick your seats: fifteen seats in three rows, and under them a summary with the number of tickets and a Clear button. Pick three seats, and the summary says Tickets: 3. Click Clear. The summary says Tickets: 0, and the three seats are still picked. Click one of them, and the summary says Tickets: -1.

So where should this state live? When two parts of a page need the same state, it lives in one place: the closest component above both. This page keeps it in two places. The Clear button reaches one and misses the other.

But moving state up is only the first step. Two more bugs come from the same mistake, in code that looks right. This lesson covers how to find the right component for a piece of state, what happens when the page needs a total, and what a component does with data that belongs to another component. It also answers one question: if moving this state up fixes the page, should every piece of state go in the top component?

The code runs in a React project made with Vite (npm create vite@latest, then React and JavaScript), the same kind of project as the last lessons. JSX doesn’t run in plain JavaScript, so you need that build step. Each example replaces src/App.jsx.

One fact, two copies

This is the whole page with the bug:

import { useState } from 'react'

const SEATS = [
  'A1', 'A2', 'A3', 'A4', 'A5',
  'B1', 'B2', 'B3', 'B4', 'B5',
  'C1', 'C2', 'C3', 'C4', 'C5',
]

function Seat({ id, onChange }) {
  const [isPicked, setIsPicked] = useState(false)

  function handleClick() {
    setIsPicked(!isPicked)
    onChange(isPicked ? -1 : 1)
  }

  return (
    <button
      className={isPicked ? 'seat picked' : 'seat'}
      aria-pressed={isPicked}
      onClick={handleClick}
    >
      {id}
    </button>
  )
}

function SeatMap({ onChange }) {
  return (
    <div className="map">
      {SEATS.map((id) => (
        <Seat key={id} id={id} onChange={onChange} />
      ))}
    </div>
  )
}

function Summary({ count, onClear }) {
  return (
    <p className="summary">
      Tickets: {count}
      <button onClick={onClear}>Clear</button>
    </p>
  )
}

export default function App() {
  const [count, setCount] = useState(0)

  return (
    <main>
      <h1>Pick your seats</h1>
      <SeatMap onChange={(change) => setCount(count + change)} />
      <Summary count={count} onClear={() => setCount(0)} />
    </main>
  )
}

A seat is a button with one piece of state: is it picked, true or false. Fifteen seats, so fifteen pieces of state. The summary is a different component, and it can’t read them. A component’s state stays inside it. No other component can read it unless it is passed down as a prop.

So the page got one more piece of state, in the App component at the top: a count. Now every click does two things. The seat flips its state. Then it calls onChange, a function from App, which adds one to the count or takes one away.

So one fact, which seats are picked, is stored twice, and nothing keeps the two copies equal. The Clear button sets the count to zero. But App can’t change a seat’s state. Only the seat can. So the seats stay picked, and the next click on a picked seat takes one away from zero: Tickets: -1. Click a second picked seat, and it says Tickets: -2.

More code could keep the two copies equal. The better fix is one copy. React’s documentation has a name for that: a single source of truth. This page has sixteen pieces of state for one fact. It needs one.

Lifting state up

Which component should hold it? Look at which components use this fact. Every seat uses it, to show whether it’s picked. The summary uses it, to count. Go up from each of them, component by component, until the lines meet. They meet at App, the closest component above both. So the state goes in App: one array that holds the picked seats.

import { useState } from 'react'

const SEATS = [
  'A1', 'A2', 'A3', 'A4', 'A5',
  'B1', 'B2', 'B3', 'B4', 'B5',
  'C1', 'C2', 'C3', 'C4', 'C5',
]

function Seat({ id, isPicked, onToggle }) {
  return (
    <button
      className={isPicked ? 'seat picked' : 'seat'}
      aria-pressed={isPicked}
      onClick={() => onToggle(id)}
    >
      {id}
    </button>
  )
}

function SeatMap({ picked, onToggle }) {
  return (
    <div className="map">
      {SEATS.map((id) => (
        <Seat key={id} id={id} isPicked={picked.includes(id)} onToggle={onToggle} />
      ))}
    </div>
  )
}

function Summary({ count, onClear }) {
  return (
    <p className="summary">
      Tickets: {count}
      <button onClick={onClear}>Clear</button>
    </p>
  )
}

export default function App() {
  const [picked, setPicked] = useState([])

  function toggle(id) {
    if (picked.includes(id)) {
      setPicked(picked.filter((seat) => seat !== id))
    } else {
      setPicked([...picked, id])
    }
  }

  return (
    <main>
      <h1>Pick your seats</h1>
      <SeatMap picked={picked} onToggle={toggle} />
      <Summary count={picked.length} onClear={() => setPicked([])} />
    </main>
  )
}

Moving state out of a child and into a parent is called lifting state up. App holds the state now, so App is its owner.

The data goes down as props. The seat map gets the array and tells each seat whether it is picked: isPicked={picked.includes(id)}. The summary gets the array’s length. But a click on a seat still has to change the state, and the seat is not the owner. So App passes down a function too, toggle. The seat calls it with its id, and App makes the new array. Data goes down. Function calls go up.

A seat has no state left. Its look comes from its props, and React’s documentation calls a component like that controlled. Pick three seats and click Clear: Tickets: 0, and no seat is picked. Sixteen pieces of state became one.

The total

Now the cinema wants a price on the page: twelve dollars a ticket. So the page gets a total. Here is a first try. Add a price above the components:

const PRICE = 12

Show the total in the summary:

function Summary({ count, total, onClear }) {
  return (
    <p className="summary">
      Tickets: {count} · Total: ${total}
      <button onClick={onClear}>Clear</button>
    </p>
  )
}

And in App, a second piece of state and one more line in the click handler, which sets the total to the number of picked seats times twelve:

export default function App() {
  const [picked, setPicked] = useState([])
  const [total, setTotal] = useState(0)

  function toggle(id) {
    if (picked.includes(id)) {
      setPicked(picked.filter((seat) => seat !== id))
    } else {
      setPicked([...picked, id])
    }
    setTotal(picked.length * PRICE)
  }

  return (
    <main>
      <h1>Pick your seats</h1>
      <SeatMap picked={picked} onToggle={toggle} />
      <Summary count={picked.length} total={total} onClear={() => setPicked([])} />
    </main>
  )
}

Pick the first seat. One ticket. Guess the total.

Tickets: 1 · Total: $0. Pick a second seat: Tickets: 2 · Total: $12. The total is one click behind. The handler reads picked, and that is still the array from before the click. Setting state doesn’t change the variable you have. It asks React for a new render, and the new array arrives in that render.

You could patch that line, and set the total from the new array:

function toggle(id) {
  const next = picked.includes(id) ? picked.filter((seat) => seat !== id) : [...picked, id]
  setPicked(next)
  setTotal(next.length * PRICE)
}

Now the clicks read $12, $24, $36. But Clear is a different piece of code. With the patch, pick three seats, click A2 to free it (Tickets: 2 · Total: $24), then click Clear: Tickets: 0 · Total: $24. Without the patch it’s the same story: three seats, then Clear, gives Tickets: 0 · Total: $24. The Clear button changed the seats and never touched the total. Every piece of code that changes the seats would have to fix the total too.

So delete that state. Make the total a constant in the component, the array’s length times the price:

export default function App() {
  const [picked, setPicked] = useState([])
  const total = picked.length * PRICE

  function toggle(id) {
    if (picked.includes(id)) {
      setPicked(picked.filter((seat) => seat !== id))
    } else {
      setPicked([...picked, id])
    }
  }

  return (
    <main>
      <h1>Pick your seats</h1>
      <SeatMap picked={picked} onToggle={toggle} />
      <Summary count={picked.length} total={total} onClear={() => setPicked([])} />
    </main>
  )
}

Every render calculates it from the seats, so it always matches them: $12, $24, $36, then $24 when you free a seat, and $0 after Clear. A value you calculate from state or props is called a derived value (you’ll also see “derived state”), and the rule is: if you can calculate it, don’t store it.

A list in the summary

The summary now lists the picked seats, and each one has a × button that removes it. Here is a first try at the summary. It takes the array from its props and puts it in state, so the button has something to change:

function Summary({ picked, total, onClear }) {
  const [seats, setSeats] = useState(picked)

  return (
    <div className="summary">
      <ul>
        {seats.map((id) => (
          <li key={id}>
            {id}
            <button aria-label={'Remove ' + id} onClick={() => setSeats(seats.filter((seat) => seat !== id))}>
              ×
            </button>
          </li>
        ))}
      </ul>
      Tickets: {seats.length} · Total: ${total}
      <button onClick={onClear}>Clear</button>
    </div>
  )
}

App now passes the array itself: <Summary picked={picked} total={total} onClear={() => setPicked([])} />. Pick three seats. Guess what the summary lists.

Nothing. Tickets: 0 · Total: $36, under three picked seats. The total is right, because App calculates it and passes it down. The list and the ticket count are wrong, because they come from the summary’s own copy.

That array was the starting value of the summary’s state. React reads a starting value only on the first render, and on that render the array was empty. After that the summary’s state doesn’t follow the prop. It is one more copy, and the copy is out of date.

The summary is not the owner of the seats. App is. So the summary keeps no state for them. It reads the prop, and to remove a seat it calls a function from App:

function Summary({ picked, total, onRemove, onClear }) {
  return (
    <div className="summary">
      <ul>
        {picked.map((id) => (
          <li key={id}>
            {id}
            <button aria-label={'Remove ' + id} onClick={() => onRemove(id)}>
              ×
            </button>
          </li>
        ))}
      </ul>
      Tickets: {picked.length} · Total: ${total}
      <button onClick={onClear}>Clear</button>
    </div>
  )
}
<Summary
  picked={picked}
  total={total}
  onRemove={toggle}
  onClear={() => setPicked([])}
/>

Removing a picked seat is the same job a click on the seat does, so App passes the same toggle. Pick A1, A2 and A3, and the summary lists all three with Tickets: 3 · Total: $36. Click the × beside A2: the list shows A1 and A3, Tickets: 2 · Total: $24, and seat A2 is free again. A seat does the same thing. A component changes only the state it holds. For everything else it asks the owner.

Everything in App?

Now the question from the start. The seats’ state is in App because two parts of the page need it. Should every piece of state go there? Try it.

The page gets a field for a promo code. With the code FRIDAY, tickets are half price. The applied code goes in App, because the total needs it. The Apply button is switched off until something is typed, so the letters in the field need state too. Put them in App with the rest. Here are the new summary, the field and the new App; SEATS, PRICE, Seat and SeatMap stay as they were:

function Summary({ picked, total, halfPrice, onRemove, onClear }) {
  return (
    <div className="summary">
      <ul>
        {picked.map((id) => (
          <li key={id}>
            {id}
            <button aria-label={'Remove ' + id} onClick={() => onRemove(id)}>
              ×
            </button>
          </li>
        ))}
      </ul>
      Tickets: {picked.length} · Total: ${total}
      {halfPrice && <span> · Half price</span>}
      <button onClick={onClear}>Clear</button>
    </div>
  )
}

function PromoField({ draft, onDraft, onApply }) {
  return (
    <form className="promo" action={onApply}>
      <label>
        Promo code <input value={draft} onChange={(e) => onDraft(e.target.value)} />
      </label>
      <button disabled={draft.trim() === ''}>Apply</button>
    </form>
  )
}

export default function App() {
  const [picked, setPicked] = useState([])
  const [code, setCode] = useState('')
  const [draft, setDraft] = useState('')
  const halfPrice = code === 'FRIDAY'
  const total = (picked.length * PRICE) / (halfPrice ? 2 : 1)

  function toggle(id) {
    if (picked.includes(id)) {
      setPicked(picked.filter((seat) => seat !== id))
    } else {
      setPicked([...picked, id])
    }
  }

  return (
    <main>
      <h1>Pick your seats</h1>
      <SeatMap picked={picked} onToggle={toggle} />
      <Summary
        picked={picked}
        total={total}
        halfPrice={halfPrice}
        onRemove={toggle}
        onClear={() => setPicked([])}
      />
      <PromoField
        draft={draft}
        onDraft={setDraft}
        onApply={() => setCode(draft.trim().toUpperCase())}
      />
    </main>
  )
}

The total is still a derived value: it now depends on two pieces of state, the seats and the code. Pick one seat, type FRIDAY, click Apply, and the summary says Tickets: 1 · Total: $6 · Half price.

The page works. Now type one letter. Guess how many components React calls again.

To count them, put a log at the top of each component:

function Seat({ id, isPicked, onToggle }) {
  console.log('call Seat')
function SeatMap({ picked, onToggle }) {
  console.log('call SeatMap')
function Summary({ picked, total, halfPrice, onRemove, onClear }) {
  console.log('call Summary')
function PromoField({ draft, onDraft, onApply }) {
  console.log('call PromoField')
export default function App() {
  console.log('call App')

Nineteen: App, SeatMap, fifteen seats, Summary and PromoField. All of them, for every letter. In development the console shows 38 lines a letter, each component twice, because the Vite template wraps the app in Strict Mode. Without Strict Mode, or in a production build, it’s 19.

React calls the component that holds the state, then every component that one returns, and every component those return. On this page that takes far less than a millisecond. But the work grows with the page, and no component except the field uses those letters. App has to hold them and pass three props to the field: draft, onDraft and onApply.

So move that state down into the field:

function PromoField({ onApply }) {
  const [draft, setDraft] = useState('')

  return (
    <form className="promo" action={() => onApply(draft.trim().toUpperCase())}>
      <label>
        Promo code <input value={draft} onChange={(e) => setDraft(e.target.value)} />
      </label>
      <button disabled={draft.trim() === ''}>Apply</button>
    </form>
  )
}

In App, delete the draft line, and the field takes one prop:

<PromoField onApply={setCode} />

Type a letter, and the console shows one call PromoField (two in development). React calls one component. Click Apply, and the field passes the finished code up: Tickets: 1 · Total: $6 · Half price. That click changes App’s state, so it calls all nineteen once more, and it should: the total changed. So state that only one component needs stays in that component.

The page ends with three pieces of state, each in its place: picked and code in App, draft in the field. The tickets count and the total are not state at all.

Where should state live?

That’s the interview question: where should state live? Three parts to the answer:

  1. In the one component that needs it.
  2. When more than one needs it, in the closest component above them all.
  3. And a value you can calculate is not state.

A component that doesn’t own a piece of state reads it from props and calls the owner’s function to change it.

In one line

Every fact is stored once, in the one component that needs it or in the closest component above all that do, and anything you can calculate from it is not state. Now you can look at any piece of state and say which component should hold it, or that it shouldn’t be state at all. Next in this course: useEffect, and when you don’t need it.

Video transcript

Three seats, zero tickets

This React page shows three picked seats and zero tickets, because its state lives in the wrong place. Pick three seats. The summary says three tickets. Now click the Clear button. Zero tickets. The three seats are still picked. Click one of them. Minus one. So where should this state live? When two parts of a page need the same state, it lives in one place: the closest component above both. This page keeps it in two places. The Clear button reaches one and misses the other. But moving state up is only the first step. Two more bugs come from the same mistake, in code that looks right. This video covers how to find the right component for a piece of state, what happens when the page needs a total, and what a component does with data that belongs to another component. And one question to think about on the way. If moving this state up fixes the page, should every piece of state go in the top component?

One fact, two copies

Start with the code. A seat is a button with one piece of state: is it picked, true or false. Fifteen seats, so fifteen pieces of state. The summary is a different component, and it can't read them. A component's state stays inside it. No other component can read it unless it is passed down as a prop. So the page got one more piece of state, in the App component at the top: a count. Now every click does two things. The seat flips its state. Then it calls a function from App, which adds one to the count or takes one away. So one fact, which seats are picked, is stored twice, and nothing keeps the two copies equal. The Clear button sets the count to zero. But App can't change a seat's state. Only the seat can. So the seats stay picked, and the next click on a picked seat takes one away from zero. More code could keep the two copies equal. The better fix is one copy. React's documentation has a name for that: single source of truth. This page has sixteen pieces of state for one fact. How many does it need?

Lifting state up

One. But in which component? Look at which components use this fact. Every seat uses it, to show whether it's picked. The summary uses it, to count. Go up from each of them, component by component, until the lines meet. They meet at App. So the state goes in App: one array that holds the picked seats. Moving state out of a child and into a parent has a name: lifting state up. The App component holds the state now, so App is its owner. The data goes down as props. The seat map gets the array and tells each seat whether it is picked. The summary gets the array's length. But a click on a seat still has to change the state, and the seat is not the owner. So App passes down a function too. The seat calls it with its id, and App makes the new array. Data goes down. Function calls go up. A seat has no state left. Now pick three seats and click Clear. Zero tickets, and no seat is picked. Sixteen pieces of state became one. Now the cinema wants a price on the page.

The total

Twelve dollars a ticket. So the page gets a total. Here is its code. A second piece of state, and one more line in the click handler: set the total to the number of picked seats times twelve. Pick the first seat. One ticket. Guess the total.

Zero dollars. Pick a second seat. Two tickets, twelve dollars. The total is one click behind. The handler reads the array of picked seats, and that is still the array from before the click. Setting state doesn't change the variable you have. It asks React for a new render. You could patch that line. But pick a third seat and click Clear. Zero tickets, twenty-four dollars. The Clear button changed the seats and never touched the total. Every piece of code that changes the seats would have to fix the total too. So delete that state. Make the total a constant in the component: the array's length times the price. Every render calculates it from the seats, so it always matches them. A value you calculate from state or props is called a derived value, and the rule is: if you can calculate it, don't store it.

A list in the summary

The summary now lists the picked seats and each one has a button that removes it. Here is the summary's code. It takes the array from its props and puts it in state, so the button has something to change. Pick three seats. Guess what the summary lists.

Nothing. Zero tickets and a total of thirty-six dollars. That array was the starting value of the summary's state. React reads a starting value only on the first render. On that render the array was empty. After that the summary's state doesn't follow the prop. It is one more copy and the copy is out of date. The summary is not the owner of the seats. App is. So the summary keeps no state for them. It reads the prop. And to remove a seat it calls a function from App. A seat does the same. A component changes only the state it holds. For everything else it asks the owner.

Everything in App?

Now the question from the start. The seats' state is in App because two parts of the page need it. Should every piece of state go there? Try it. The page gets a field for a promo code. With the code Friday, tickets are half price. The applied code goes in App, because the total needs it. The Apply button is switched off until something is typed, so the letters in the field need state too. Put them in App with the rest. Type one letter. Guess how many components React calls again.

Nineteen. All of them. React calls the component that holds the state, then every component that one returns, and every component those return. On this page that takes far less than a millisecond. But the work grows with the page, and no component except the field uses those letters. App has to hold them and pass three props to the field. So move that state down into the field. Now the field takes one prop. Type a letter, and React calls one component. Click Apply, and the field passes the finished code up. So state that only one component needs stays in that component. In an interview, the question is: where should state live? In the one component that needs it. When more than one needs it, in the closest component above them all. And a value you can calculate is not state.

Next: useEffect

Now you can look at any piece of state and say which component should hold it, or that it shouldn't be state at all. Next in this course: useEffect, and when you don't need it. The next video is on screen now.

Learn more