DEV Community

Cover image for State lives in the parent, the child just asks
nayem
nayem

Posted on Originally published at nayemalam.com

State lives in the parent, the child just asks

The SeatFinder check-in button lives in the guest row. It is a small thing, one button per guest, and the checked-in state looks like it belongs right there next to it, inside the row component. Put it there and the button works, it flips to Checked in on tap, while the header count says 0 of 80 where it should say 3 of 80. The row knew. The parent had no idea. (The row knew, the parent had no idea, and that gap was the bug.)

The tempting next move is worse: change the prop directly from the child, as if the row could reach up and rewrite what the parent passed down. React ignores it. Props are read-only by design, and a child that mutates them is writing on a copy that nobody re-reads. One-way data flow is not a diagram in the docs, it is the rule that decides where state is allowed to live.

The fix has a name in the React docs, lifting state up, and it is simpler than it sounds. The state moves into the closest parent that needs to see it, and the parent passes a callback down to the child. The child calls the callback when something happens, the parent updates the state, and the new value flows back down as a prop. Props go down, callbacks go up, and the circle is complete.

the version that did not work

Here is that version, stripped down so the shape is easy to see. The state lives in the row, the button works, and the parent is blind.

GuestRow.tsx

type Guest = { id: string; name: string };

function GuestRow({ guest }: { guest: Guest }) {
  const [checked, setChecked] = useState(false);

  return (
    <li>
      {guest.name}
      <button
        type='button'
        onClick={() => setChecked(true)}
        disabled={checked}
      >
        {checked ? 'Checked in' : 'Check in'}
      </button>
    </li>
  );
}

function SeatingChart({ guests }: { guests: Guest[] }) {
  return (
    <ul>
      {guests.map((guest) => (
        <GuestRow key={guest.id} guest={guest} />
      ))}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

This compiles, it runs, and the button even works. The problem is the boundary. The checked-in state belongs to the row, so nothing outside the row can read it. The header count, the progress bar, the export button that needs the checked-in list, all of them are locked out. State that lives in the wrong component is not broken, it is just unreachable, and unreachable state gets duplicated. The usual workaround is a second copy of the same state in the parent, just to feed the header, and then the two copies drift apart, because nothing keeps them in sync.

the fix: lift the state into the parent

The fix is one move: take the useState call out of the row and put it in the parent. The row keeps the button, it just loses the state. The parent owns the state and hands the row two props, the current value and a callback to ask for a change. When the button is tapped, the row calls onCheckIn, the parent updates its state, React re-renders, and the new checked value flows back down into the row as a prop.

SeatingChart.tsx

type Guest = { id: string; name: string };

function GuestRow({ guest, checked, onCheckIn }: {
  guest: Guest;
  checked: boolean;
  onCheckIn: () => void;
}) {
  return (
    <li>
      {guest.name}
      <button
        type='button'
        onClick={onCheckIn}
        disabled={checked}
      >
        {checked ? 'Checked in' : 'Check in'}
      </button>
    </li>
  );
}

function SeatingChart({ guests }: { guests: Guest[] }) {
  const [checkedIn, setCheckedIn] = useState<Record<string, boolean>>({});

  return (
    <div>
      <p>
        {Object.values(checkedIn).filter(Boolean).length} of {guests.length} checked in
      </p>
      <ul>
        {guests.map((guest) => (
          <GuestRow
            key={guest.id}
            guest={guest}
            checked={!!checkedIn[guest.id]}
            onCheckIn={() =>
              setCheckedIn((prev) => ({ ...prev, [guest.id]: true }))
            }
          />
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Read it as a loop. The parent renders the row with a checked prop and an onCheckIn prop. The row renders the button. A tap calls the callback. The callback updates the parent state. The parent re-renders and passes the new checked value down. Nothing reaches up, nothing reaches across. Every change travels the same road, down as data, up as a callback, and that is what makes the flow easy to trace when something goes wrong.

name the prop after the event

Name the callback prop after the event, onCheckIn, onToggle, onSelect, not after the setter. Passing setCheckedIn straight down as a prop works, and for a tiny example it is fine, but the wrapper reads better once the parent has anything to decide. Maybe checking in also stamps a time, or skips guests who already checked in somewhere else. The wrapper is where that logic lives, and the child stays simple about it, which is exactly what you want from a row component. The child knows a button was pressed. The parent decides what that means.

Try it: the button lives in the child, the count lives in the parent
Try it live on nayemalam.com.

Tap a few guests in and watch the header count move. The buttons live in the child rows, the count lives in the parent, and the only connection between them is the onCheckIn callback. Reset clears the parent state, and every row follows, because the rows only ever render what the parent passes down.

the stale-state trap

One more trap lives in the callback itself. A state update that reads the current value can go stale when two updates run in the same handler. The symptom is a button that adds one when the handler asks for two. The bug is stale state: both updates read the same value, so the second overwrites the first instead of building on it.

DoubleCounter.tsx

function DoubleCounter() {
  const [count, setCount] = useState(0);

  function addTwo() {
    setCount(count + 1);
    setCount(count + 1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button type='button' onClick={addTwo}>Add two</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Both calls read the same count, because React batches updates from the same event and the state variable stays the same between the two lines. The fix is the functional form, where each update gets the latest value instead of the stale one.

DoubleCounter.tsx

function addTwo() {
  setCount((c) => c + 1);
  setCount((c) => c + 1);
}
Enter fullscreen mode Exit fullscreen mode

The functional form is the default any time the new state depends on the old state, which in practice means most callbacks a child calls. It is a small habit and it removes a whole class of off-by-one bugs.

when two children need the same state

The same move scales up. When two siblings need the same state, a search box and a list, a filter and a count, the state lifts into their shared parent, and both children get props from the same source. That is still the same pattern, one owner, values down, callbacks up. If the state keeps climbing, past three or four levels of props, that is the point where React context starts earning its keep, but most of the time the shared parent is close by, and lifting one level is all it takes.

State has an address, and the address matters as much as the value. State in the child is invisible to the parent. State in the parent is visible to every child that needs it, through props, and changeable by any of them, through callbacks. Props go down, callbacks go up. Keep that boundary clean and the components stay small, the bugs stay easy to find, and the header says 3 of 80.


Originally posted on nayemalam.com/blog.

Top comments (0)