useState Deep Dive
useState stores state in the component Fiber node linked list and provides a setter that schedules a re-render.
Mental Model
"The Locker: Each useState call reserves a numbered locker in your component Fiber. React opens lockers in exact order on each render."
Interactive Engine Simulation
Invariant:The stability of this sequence is what allows React to persist state across asynchronous render cycles.
Executable Code Snippet
1function MultiState() {
2 // Each call corresponds to a slot in an internal array
3 const [name, setName] = useState("React"); // Slot 0
4 const [ver, setVer] = useState(19); // Slot 1
5
6 return <h1>{name} v{ver}</h1>;
7}- 01.Component re-renders are triggered by state or prop changes.
- 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
- 03.Automatic batching optimizes multiple state updates into a single render cycle.
01. Slot-based Persistence
React doesn't use magic to know which state belongs to which component. Internally, every Fiber node (component instance) has a `memoizedState` property that holds a **linked list of hook objects**. When you call `useState`, React simply returns the value at the current "pointer" and moves the pointer to the next slot.
Internal Hook Map
(state)
(effect)
(state)
02. Why Order Matters
This internal architecture is why the **Rules of Hooks** exist. If you wrap a hook in an `if` statement, and that condition changes, the slots will shift. React will return the wrong state for the wrong hook, leading to chaotic and untraceable bugs.
Senior Insight
"Think of 'useState' as an index into a table. The index is not a name, it's just 'the nth time this function was called.' This simplicity is what makes hooks so powerful and composable."