~/alexsh.blog

$ cat react-internals/05-how-hooks-work.md

How Hooks Work

February 9, 20261 min readpart 05/13

Hooks are a linked list stored on fiber.memoizedState. No magic — just pointers.

The Linked List

Each hook call during render either creates a new node (mount) or advances to the next existing one (update). This is why hooks must be called in the same order every render — React uses call order, not names.

diagramtext
fiber.memoizedState → hook1 (useState)
                          ↓ next
                        hook2 (useEffect)
                          ↓ next
                        hook3 (useMemo)
                          ↓ next
                        null

useState is useReducer

useState is implemented as useReducer with a trivial reducer. When you call setState, React enqueues an update on the hook's circular queue, marks lanes on the Fiber, and schedules a re-render. All queued updates are processed together — this is batching.

codetsx
function basicStateReducer(state, action) {
  return typeof action === 'function' ? action(state) : action;
}

// useState(initialValue) ≡ useReducer(basicStateReducer, initialValue)

useEffect Execution

Effects are stored as a separate linked list on fiber.updateQueue. Dependency comparison uses Object.is() on each element — shallow, reference-based. useEffect runs asynchronously after paint. useLayoutEffect runs synchronously after DOM mutation, before paint.

useMemo / useCallback

Simpler than you'd expect. useMemo stores [value, deps] and recomputes only if deps change. useCallback(fn, deps) is literally useMemo(() => fn, deps).

useRef

The simplest hook. Stores { current: initialValue } on mount, returns the same object forever. Same identity = no re-renders on mutation.

Further reading