الانتقال إلى المحتوى
FrontendReact· 8 دقائق للقراءة

State Lives at a Position in the Tree, Not Inside the Component

React keeps state at a slot in the UI tree. Same type in the same slot keeps it; a new key starts fresh.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • React 19
محتويات المقال

A support agent opens Alice's ticket and starts a reply: "Hi Alice, your refund was approved…". A chat pings, she clicks Bob's ticket in the sidebar, and the screen switches to Bob: his name, his order, his message history. Everything except the reply box, which still holds the text written for Alice. She skims it, hits Send, and Bob gets someone else's refund news. The component is <ReplyBox ticket={ticket} />, and the developer who wrote it was sure that a different ticket meant a different reply box.

The common misconception

The belief: state lives inside the component, the way fields live inside an object. Render <ReplyBox ticket={bob} /> instead of <ReplyBox ticket={alice} /> and you have a new component with new state. Whether state is kept or reset depends on what you render.

It's a natural model. Class components really did keep this.state on an instance, and a JSX tag looks a lot like a constructor call. useState sits inside the function body, so it reads like a local variable the function owns. And part of it is true: state is isolated per component, so two <Counter /> tags side by side each count on their own. The mistake is in what React treats as "one component": not the props, not the data on screen, and not the line of JSX you wrote.

What actually happens

React holds the state, not your function

From your JSX, React builds a : which component sits under which. Your component function is called on every render and keeps nothing between calls. When it calls useState, React hands it the value stored for that spot in the tree. React's docs state the rule plainly: a component keeps its state for as long as it's rendered at its position in the UI tree. Remove it, or render a different component type at that position, and React discards the state.

Same type, same position: the state stays

On every render, React compares the new tree with the previous one position by position, as part of . If the same component type sits at the same position, React treats it as the same component: it passes the new props and keeps the state. That's the support bug. ReplyBox is still a ReplyBox at the same spot, so React gives it Bob's ticket as a prop and keeps Alice's draft. The initial value you pass to useState doesn't help either: React uses it on the first render and ignores it afterwards.

Position is in the tree, not in your JSX

Two lines of JSX can be one position. If an if returns <main><ReplyBox /></main> from one branch and the same structure from the other, both land as the same child of the same parent, so the state carries over. A ternary works the same way: isVip ? <ReplyBox vip /> : <ReplyBox /> is one slot with one state.

The reverse holds too. {isVip && <ReplyBox vip />} followed by {!isVip && <ReplyBox />} gives the parent two child slots, and only one is filled at a time. Flipping isVip moves the component to the other slot, so it starts over. And as the first article in this path showed, changing the element type above a component, like a <div> wrapper that becomes a <section>, resets everything below it.

What changes between two rendersSame component to React?State
<ReplyBox ticket={alice} /> becomes <ReplyBox ticket={bob} />Yes: same type, same positionKept
cond ? <ReplyBox vip /> : <ReplyBox /> flipsYes: one slotKept
{cond && <ReplyBox vip />}{!cond && <ReplyBox />} flipsNo: two different slotsReset
The wrapper changes from <div> to <section>No: the parent's type changedReset for the whole subtree
key={alice.id} becomes key={bob.id}No: a different identityReset

A key turns "same position" into "same item"

A isn't only for lists. On any component, it adds an identity on top of the position: React keeps the state only when both the type and the key match. A reply to Alice is conceptually a different reply box from one to Bob, so say so:

TSX TicketPage.tsx
import { useState } from "react";type Ticket = { id: string; customer: string };function ReplyBox({ ticket }: { ticket: Ticket }) {  const [draft, setDraft] = useState("");  return (    <>      <textarea value={draft} onChange={(e) => setDraft(e.target.value)} />      <button onClick={() => sendReply(ticket.id, draft)}>        Reply to {ticket.customer}      </button>    </>  );}export function TicketPage({ ticket }: { ticket: Ticket }) {  // Same type at the same position: Bob's ticket keeps Alice's draft  return <ReplyBox ticket={ticket} />;}

With key={ticket.id}, switching tickets changes the key, so React unmounts Alice's ReplyBox, drops her draft and mounts a fresh one for Bob, with a new <textarea> DOM node as well. Keys only need to be unique among siblings, because they name a position within the parent, so ticket.id here can't clash with list keys elsewhere.

Keeping state after a component disappears

Sometimes you want the opposite: drafts that survive switching tickets, one per ticket. State dies with its position, so it has to live in something that stays mounted. The usual answer is to store it one level up and key the data, not the component:

TSX ReplyPanel.tsx
import { useState } from "react";type Drafts = Record<string, string>;export function ReplyPanel({ ticketId }: { ticketId: string }) {  // No key on purpose: the panel keeps its position, so the map survives  const [drafts, setDrafts] = useState<Drafts>({});  const draft = drafts[ticketId] ?? "";  return (    <textarea      value={draft}      onChange={(e) => setDrafts({ ...drafts, [ticketId]: e.target.value })}    />  );}

This time the same-position rule works for you: the panel's state survives every switch, and each ticket reads its own entry. React's docs list two more options: hide inactive views with CSS instead of unmounting them, or keep drafts in localStorage so they survive a reload too.

How to apply it in your project

  1. Look for state that leaks between itemsSwitch between two records on every master-detail screen: tickets, contacts, products. Typed text, a selected tab, an open section or a scroll position that follows you to the next record is state staying at its position.
  2. Key the view where the item changesPut key={item.id} on the component that represents one item, as high in the tree as the reset should reach. Everything below it starts fresh for each item.
  3. Replace reset Effects with keysSearch for Effects whose only job is calling setters when a prop changes, like setDraft("") on [ticket.id]. A key on the component usually removes them entirely.
  4. Decide which state must outlive its componentIf users expect a draft or a filter to survive switching away, store it per id in a parent that stays mounted, or hide the view instead of unmounting it.

Key takeaways

  • React stores state at a position in the UI tree; your component function only reads it.
  • The same component type at the same position keeps its state whatever the props, and useState's initial value is used only once.
  • Position means the slot in the tree, not the line of JSX: one ternary is one slot, two && expressions are two.
  • A different key makes a different component: key by item.id to reset per item, and lift state up when it must outlive the component.

📚 المصادر

  1. Preserving and Resetting State — React
  2. useState — React API Reference
  3. You Might Not Need an Effect — React
  4. <Activity> — React API Reference

التعليقات (0)