
State Lives at a Position in the Tree, Not Inside the Component
- كاتب موثّق
- React 19
محتويات المقال
<ReplyBox ticket={ticket} />, and the developer who wrote it was sure that a different ticket meant a different reply box.
The common misconception
<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.
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
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
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
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.
{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.
<ReplyBox ticket={alice} /> becomes <ReplyBox ticket={bob} /> | ||
cond ? <ReplyBox vip /> : <ReplyBox /> flips | ||
{cond && <ReplyBox vip />}{!cond && <ReplyBox />} flips | ||
<div> to <section> | ||
key={alice.id} becomes key={bob.id} |
A key turns "same position" into "same item"
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} />;}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 }) { // A new key is a new identity: every ticket starts with an empty draft return <ReplyBox key={ticket.id} ticket={ticket} />;}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
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 })} /> );}localStorage so they survive a reload too.
How to apply it in your project
Look for state that leaks between items Switch 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. Key the view where the item changes Put 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.Replace reset Effects with keys Search 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.Decide which state must outlive its component If 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 keymakes a different component: key byitem.idto reset per item, and lift state up when it must outlive the component.
التعليقات (0)