Props and state
State belongs to a position in the tree
Recognize when React preserves component state and use identity or a key when the interface needs a deliberate reset.
State is not stored inside a JSX tag. React associates it with a component type at a position in the rendered tree.
If the same component stays in the same position, React preserves its state. Changing its props does not reset it.
This matters for an editable chat draft:
<Chat contact={selectedContact} />
Switching contacts changes the prop, but Chat remains in the same tree position. Its input state stays. That could send one person’s draft to another person.
Give each independent draft an identity:
<Chat key={selectedContact.id} contact={selectedContact} />
When the key changes, React removes the old component state and creates a new subtree.
Keys are not only for lists. They tell React which identity occupies a position among siblings. Use a key to reset state when the product meaning changes, not as a general way to force rendering.
Changing the component type also resets state. This is one reason not to define component functions inside another component: every render creates a new function identity.
Decide whether state should survive before adding a key. A tab switch may preserve an unfinished form. A recipient switch may need a clean draft.
Build a small input that switches between two contacts. Test it with and without the key and choose the behavior deliberately.
Lesson completed