Lesson 17-Core Principles and Source Code Analysis of React Hooks

Since their introduction in React 16.8, React Hooks have revolutionized function component development, enabling them to match the capabilities of class components. This tutorial delves into the core principles of Hooks, analyzes the implementation details of each commonly used Hook, and examines their source code from React 18 (react and react-reconciler). By the end, you’ll thoroughly understand how Hooks work and their implementation within the Fiber architecture.

Hooks Core Principles

What Are Hooks?

Hooks are a set of functions provided by React that allow function components to manage state, handle side effects, access context, and more. They address several pain points of class components:

  • Difficult Logic Reuse: Class components rely on higher-order components (HOCs) or render props, leading to complex and hard-to-maintain code.
  • Fragmented Lifecycle Logic: Related logic is scattered across different lifecycle methods.
  • this Binding Issues: Class components require handling this binding.

Example: Class Component vs. Function Component

Class Component:

class Counter extends React.Component {
  state = { count: 0 };
  componentDidMount() {
    document.title = `Count: ${this.state.count}`;
  }
  componentDidUpdate() {
    document.title = `Count: ${this.state.count}`;
  }
  render() {
    return (
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        {this.state.count}
      </button>
    );
  }
}

Using Hooks:

function Counter() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Hooks Implementation Foundation: Fiber Architecture

Hooks rely on React’s Fiber architecture. Each function component corresponds to a Fiber node, and Hooks’ state and side effects are stored and managed in the Fiber’s memoizedState property.

Fiber Node Structure

const fiber = {
  tag: FunctionComponent,      // Function component type
  type: Counter,               // Component function
  memoizedState: null,         // Hooks state linked list
  updateQueue: null,           // Update queue
  child: null,                 // Child Fiber
  sibling: null,               // Sibling Fiber
  return: null                 // Parent Fiber
};
  • memoizedState: Stores Hooks’ state as a linked list.
  • Call Order: React uses the order of Hook calls to locate each Hook’s state.

Hooks Call Rules

  • Top-Level Only: Hooks must be called at the top level of function components to ensure consistent call order across renders.
  • No Conditionals or Loops: Avoid using Hooks in conditionals or loops to prevent state misalignment.

Example: Incorrect Usage

function BadComponent() {
  if (Math.random() > 0.5) {
    useState(0); // Error: Conditional call disrupts order
  }
  const [value] = useState(1);
  return <div>{value}</div>;
}

Hooks Workflow

  1. Mount Phase: During initial rendering, initialize Hooks’ state and bind it to the Fiber.
  2. Update Phase: Reuse previous Hooks’ state based on call order, processing update logic.

Hooks Implementation Principles

Global State Management

React manages Hooks’ implementation via a global variable currentDispatcher:

// react/src/ReactCurrentDispatcher.js
const ReactCurrentDispatcher = {
  current: null
};
  • During function component rendering, current points to HooksDispatcherOnMount (mount) or HooksDispatcherOnUpdate (update).
  • Each Hook function (e.g., useState) retrieves its implementation from current.

Hooks State Linked List

Hooks’ state is stored as a singly linked list in the Fiber’s memoizedState, with each node corresponding to a Hook call:

const hook = {
  memoizedState: null,  // Hook’s current value (e.g., useState’s state)
  queue: null,          // Update queue
  next: null            // Next Hook
};

Example: Multiple Hooks

function Component() {
  const [a] = useState(1);
  const [b] = useState(2);
  return <div>{a + b}</div>;
}

Fiber’s memoizedState:

hook1: { memoizedState: 1, queue: {...}, next: hook2 }
hook2: { memoizedState: 2, queue: {...}, next: null }

Hooks Execution in Render Phase

During the Fiber’s render phase, React calls the function component, executes each Hook sequentially, and maintains global pointers currentlyRenderingFiber and workInProgressHook.

Source Code Analysis of Common Hooks

Below, we analyze the source code of each common Hook, based on React 18’s react and react-reconciler.

useState Source Analysis

Role

useState provides state management for function components, returning a state value and an update function.

Example

const [count, setCount] = useState(0);

Source Analysis

useState is defined in react/src/ReactHooks.js:

function useState(initialState) {
  const dispatcher = ReactCurrentDispatcher.current;
  return dispatcher.useState(initialState);
}
Mount Phase: mountState
// react-reconciler/src/ReactFiberHooks.js
function mountState(initialState) {
  const hook = mountWorkInProgressHook(); // Create new Hook node
  const initial = typeof initialState === 'function' ? initialState() : initialState;
  hook.memoizedState = hook.baseState = initial; // Initialize state
  hook.queue = {
    pending: null,       // Pending updates
    dispatch: null,      // setState function
    lastRenderedState: initial // Last rendered state
  };
  const dispatch = (hook.queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber, hook.queue));
  return [hook.memoizedState, dispatch];
}

function mountWorkInProgressHook() {
  const hook = {
    memoizedState: null,
    baseState: null,
    baseQueue: null,
    queue: null,
    next: null
  };
  if (workInProgressHook === null) {
    currentlyRenderingFiber.memoizedState = workInProgressHook = hook;
  } else {
    workInProgressHook = workInProgressHook.next = hook;
  }
  return hook;
}
Update Phase: updateState
function updateState(initialState) {
  return updateReducer(basicStateReducer, initialState);
}

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

function updateReducer(reducer) {
  const hook = updateWorkInProgressHook(); // Get current Hook
  const queue = hook.queue;
  const pending = queue.pending;
  let newState = hook.memoizedState;

  if (pending !== null) {
    queue.pending = null; // Clear update queue
    let update = pending.next;
    do {
      newState = reducer(newState, update.action); // Apply update
      update = update.next;
    } while (update !== null && update !== pending.next);
  }
  hook.memoizedState = newState;
  return [newState, queue.dispatch];
}
Update Trigger: dispatchAction
function dispatchAction(fiber, queue, action) {
  const update = { action, next: null };
  const pending = queue.pending;
  if (pending === null) {
    update.next = update; // Circular linked list
  } else {
    update.next = pending.next;
    pending.next = update;
  }
  queue.pending = update;
  scheduleUpdateOnFiber(fiber); // Trigger update
}

Principle Summary

  • Mount: Creates Hook node, initializes state, returns [state, dispatch].
  • Update: Reuses Hook node, processes update queue, generates new state.
  • Update Queue: Circular linked list stores multiple setState calls.

useReducer Source Analysis

Role

useReducer is an enhanced version of useState, suitable for complex state logic.

Example

const [state, dispatch] = useReducer(reducer, initialState);

Source Analysis

Mount Phase: mountReducer
function mountReducer(reducer, initialArg) {
  const hook = mountWorkInProgressHook();
  hook.memoizedState = initialArg;
  hook.queue = { pending: null, dispatch: null, lastRenderedState: initialArg };
  const dispatch = (hook.queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber, hook.queue));
  return [hook.memoizedState, dispatch];
}
Update Phase: updateReducer

Reuses updateReducer function, same as useState.

Principle Summary

  • Similar to useState, but allows custom reducer function.
  • Shares the same update queue mechanism.

useContext Source Analysis

Role

useContext accesses context values, avoiding deep prop passing.

Example

const value = useContext(MyContext);

Source Analysis

function useContext(context) {
  const dispatcher = ReactCurrentDispatcher.current;
  return dispatcher.useContext(context);
}

function readContext(context) {
  const value = context._currentValue; // Get current context value
  return value;
}
  • In Fiber, useContext tracks context changes via dependencies:
function updateContextConsumer(fiber) {
  const context = fiber.type;
  const newValue = readContext(context);
  return newValue;
}

Principle Summary

  • Directly reads _currentValue from global context object.
  • Doesn’t rely on Hook linked list, resolved during rendering.

useEffect Source Analysis

Role

useEffect handles side effects like data fetching or subscriptions.

Example

useEffect(() => {
  document.title = 'Hello';
  return () => document.title = 'Goodbye';
}, [dependency]);

Source Analysis

Mount Phase: mountEffect
function mountEffect(create, deps) {
  const hook = mountWorkInProgressHook();
  hook.memoizedState = pushEffect(Effect | Passive, create, null, deps);
  return hook.memoizedState;
}

function pushEffect(tag, create, destroy, deps) {
  const effect = { tag, create, destroy, deps, next: null };
  const fiber = currentlyRenderingFiber;
  let firstEffect = fiber.effectTag === NoEffect ? null : fiber.firstEffect;
  if (firstEffect === null) {
    fiber.firstEffect = fiber.lastEffect = effect;
  } else {
    fiber.lastEffect.next = effect;
    fiber.lastEffect = effect;
  }
  return effect;
}
Update Phase: updateEffect
function updateEffect(create, deps) {
  const hook = updateWorkInProgressHook();
  const prevEffect = hook.memoizedState;
  const prevDeps = prevEffect.deps;

  if (areHookInputsEqual(deps, prevDeps)) {
    return; // Dependencies unchanged, skip
  }
  hook.memoizedState = pushEffect(Effect | Passive, create, null, deps);
}
Execution Timing

Executed in commit phase’s flushPassiveEffects:

function flushPassiveEffects() {
  let effect = rootWithPendingPassiveEffects.firstEffect;
  while (effect !== null) {
    const { create, destroy } = effect;
    commitHookEffectList(UnmountPassive, MountPassive, effect);
    effect = effect.next;
  }
}

Principle Summary

  • Uses effect linked list to store side effects.
  • Re-registers on dependency changes.
  • Executes asynchronously in commit phase.

useRef Source Analysis

Role

useRef creates mutable reference objects, often for DOM access or persistent values.

Example

const ref = useRef(null);

Source Analysis

Mount Phase: mountRef
function mountRef(initialValue) {
  const hook = mountWorkInProgressHook();
  const ref = { current: initialValue };
  hook.memoizedState = ref;
  return ref;
}
Update Phase: updateRef
function updateRef(initialValue) {
  const hook = updateWorkInProgressHook();
  return hook.memoizedState;
}

Principle Summary

  • Returns a simple { current: value } object.
  • Doesn’t trigger re-renders.

useLayoutEffect Source Analysis

Role

useLayoutEffect is similar to useEffect but executes synchronously after DOM updates.

Source Analysis

Similar to useEffect, but with a different tag:

function mountLayoutEffect(create, deps) {
  const hook = mountWorkInProgressHook();
  hook.memoizedState = pushEffect(Effect | Layout, create, null, deps);
}
  • Executed synchronously in commitLayoutEffects.

Principle Summary

  • Shares implementation with useEffect, differing in execution timing (sync vs. async).

useMemo Source Analysis

Role

useMemo caches computation results to avoid redundant calculations.

Example

const value = useMemo(() => expensiveComputation(a, b), [a, b]);

Source Analysis

Mount Phase: mountMemo
function mountMemo(nextCreate, deps) {
  const hook = mountWorkInProgressHook();
  const value = nextCreate();
  hook.memoizedState = [value, deps];
  return value;
}
Update Phase: updateMemo
function updateMemo(nextCreate, deps) {
  const hook = updateWorkInProgressHook();
  const [prevValue, prevDeps] = hook.memoizedState;
  if (areHookInputsEqual(deps, prevDeps)) {
    return prevValue;
  }
  const value = nextCreate();
  hook.memoizedState = [value, deps];
  return value;
}

Principle Summary

  • Caches value and dependencies, returning cached value if dependencies are unchanged.

useCallback Source Analysis

Role

useCallback caches callback functions to prevent unnecessary child re-renders.

Example

const handleClick = useCallback(() => console.log(a), [a]);

Source Analysis

Built on useMemo:

function useCallback(callback, deps) {
  return useMemo(() => callback, deps);
}

Principle Summary

  • Returns a cached function reference, stable if dependencies are unchanged.

useId Source Analysis

Role

useId generates unique IDs for server-side rendering consistency.

Example

const id = useId(); // e.g., ":r1:"

Source Analysis

function useId() {
  const task = getCurrentTask();
  const id = task.idPrefix + task.nextId++;
  return id;
}

Principle Summary

  • Generates IDs based on a global counter in the Fiber tree.

useTransition Source Analysis

Role

useTransition marks non-urgent updates to improve interaction experience.

Example

const [isPending, startTransition] = useTransition();

Source Analysis

function mountTransition() {
  const [isPending, setPending] = useState(false);
  const start = (callback) => {
    setPending(true);
    scheduleUpdateOnFiber(currentlyRenderingFiber, TransitionLane);
    callback();
    setPending(false);
  };
  return [isPending, start];
}

Principle Summary

  • Schedules updates with low-priority TransitionLane.

Summary and Source Debugging

Hooks manage state and side effects through the Fiber’s memoizedState linked list and scheduling mechanisms. Their core lies in:

  • Linked List Structure: Sequentially stores Hook states.
  • Dispatcher: Dynamically switches between mount/update logic.
  • Effect Linked List: Uniformly handles side effects.

Share your love