Lesson 24-React Source Code Architecture

React Core Architecture Source Code

Core Concepts of Fiber Architecture

Double Buffering Mechanism Implementation:

// ReactFiberWorkLoop.old.js
function workLoopConcurrent() {
  // The Fiber tree being built (WorkInProgress Tree)
  while (workInProgress !== null && !shouldYield()) {
    performUnitOfWork(workInProgress)
  }

  // After completing the current frame, WorkInProgress Tree becomes Current Tree
  if (workInProgress === null) {
    commitRoot(root)
  }
}

Priority Scheduling System:

// ReactFiberLane.old.js
export const NoLane: Lane = 0b0000000000000000000000000000000
export const SyncLane: Lane = 0b0000000000000000000000000000001
export const InputContinuousLane: Lane = 0b0000000000000000000000000000010
// ...other priority Lane definitions

function requestUpdateLane(fiber) {
  // Returns priority Lane based on component type and interaction
  if (fiber.mode & ConcurrentMode) {
    if (isEventHandle(fiber)) {
      return InputContinuousLane
    }
    return DefaultLane
  }
  return SyncLane
}

Virtual DOM and Diff Algorithm

Fiber Node Structure:

// ReactFiber.old.js
function FiberNode(
  tag: WorkTag,
  pendingProps: mixed,
  key: null | string,
  mode: TypeOfMode,
) {
  // Instance properties
  this.tag = tag
  this.key = key
  this.elementType = null
  this.type = null
  this.stateNode = null

  // Fiber tree structure
  this.return = null
  this.child = null
  this.sibling = null
  this.index = 0

  // Update-related properties
  this.pendingProps = pendingProps
  this.memoizedProps = null
  this.memoizedState = null
  this.updateQueue = null
  this.lanes = NoLanes
}

Core Logic of Diff Algorithm:

// ReactChildFiber.old.js
function reconcileChildrenArray(
  returnFiber: Fiber,
  currentFirstChild: Fiber | null,
  newChildren: Array<*>,
  lanes: Lanes,
) {
  let resultingFirstChild: Fiber | null = null
  let previousNewFiber: Fiber | null = null

  let oldFiber = currentFirstChild
  let lastPlacedIndex = 0
  let newIdx = 0
  let nextOldFiber = null

  for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
    if (oldFiber.index > newIdx) {
      nextOldFiber = oldFiber
      oldFiber = null
    } else {
      nextOldFiber = oldFiber.sibling
    }

    const newFiber = updateSlot(
      returnFiber,
      oldFiber,
      newChildren[newIdx],
      lanes,
    )

    if (newFiber === null) {
      // Key mismatch, break comparison
      if (oldFiber === null) {
        oldFiber = nextOldFiber
      }
      break
    }

    // Record the last placed position
    lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx)

    if (previousNewFiber === null) {
      resultingFirstChild = newFiber
    } else {
      previousNewFiber.sibling = newFiber
    }
    previousNewFiber = newFiber
    oldFiber = nextOldFiber
  }

  // ...remaining node handling logic
}

Event System Synthesis Mechanism

Event Registration and Delegation:

// ReactEventListener.js
const eventSystemFlags = {
  captured: 1,
  bubbled: 2,
  passive: 4,
}

function listenToNativeEvent(
  topLevelType,
  targetContainer,
  eventSystemFlags,
) {
  // All events are delegated to document/root node
  const listener = createEventListenerWrapper(topLevelType, eventSystemFlags)
  document.addEventListener(
    topLevelType.toLowerCase(),
    listener,
    supportsPassive ? { capture: !!eventSystemFlags } : false
  )
}

// Synthetic event object
class SyntheticEvent {
  constructor(dispatchConfig, targetInst, nativeEvent) {
    this._dispatchListeners = null
    this._dispatchInstances = null
    this.nativeEvent = nativeEvent
    this.target = getEventTarget(nativeEvent)
    this.currentTarget = targetInst ? getInstanceFromNode(targetInst) : null
  }

  persist() {
    // Allow asynchronous access to event properties
    this._persisted = true
  }
}

Event Bubbling Process:

  1. Event triggers start at the capture phase from document/root node.
  2. Execute capture event handlers for corresponding Fiber nodes.
  3. Reach the target node and execute bubbling phase handlers.
  4. Use event.stopPropagation() to interrupt propagation.

Hooks Internal Implementation

Hooks Linked List Structure:

// ReactFiberHooks.old.js
let firstWorkInProgressHook: Hook | null = null
let currentHook: Hook | null = null

function updateWorkInProgressHook() {
  // Create new Hook node
  const hook: Hook = {
    memoizedState: null,
    baseState: null,
    baseQueue: null,
    queue: null,
    next: null,
  }

  if (workInProgressHook === null) {
    // First render
    currentlyRenderingFiber.memoizedState = workInProgressHook = hook
  } else {
    // Update render, append to linked list
    workInProgressHook = workInProgressHook.next = hook
  }

  return workInProgressHook
}

Call Order Validation:

// ReactFiberHooks.old.js
function checkHooksOrder() {
  let hook: Hook | null = currentlyRenderingFiber.memoizedState
  let previousIsLayout = false

  while (hook !== null) {
    if (hook.lane === SyncLane) {
      if (previousIsLayout) {
        // Violates Hook call order rules
        throw new Error('Rendered fewer hooks than expected')
      }
    } else {
      previousIsLayout = true
    }
    hook = hook.next
  }
}

Component Lifecycle Management

Class Component Lifecycle:

// ReactFiberClassComponent.old.js
function mountClassInstance(
  workInProgress,
  ctor,
  props,
  renderLanes,
) {
  // Initialize state
  const instance = new ctor(props)
  workInProgress.stateNode = instance

  // Bind methods
  instance.updater = classComponentUpdater

  // Execute lifecycle
  if (typeof instance.componentWillMount === 'function') {
    instance.componentWillMount()
  }

  // Initial render
  const value = instance.render()
  reconcileChildren(
    workInProgress,
    null,
    value,
    renderLanes,
  )

  // Complete mount
  if (typeof instance.componentDidMount === 'function') {
    workInProgress.flags |= Update
  }
}

Function Component Update Process:

// ReactFiberHooks.old.js
function updateFunctionComponent(
  current,
  workInProgress,
  Component,
  nextProps,
  renderLanes,
) {
  // Execute function component
  let nextChildren
  prepareToReadContext(workInProgress, renderLanes)
  nextChildren = renderWithHooks(
    current,
    workInProgress,
    Component,
    nextProps,
    renderLanes,
  )

  // Reconcile children
  reconcileChildren(
    current,
    workInProgress,
    nextChildren,
    renderLanes,
  )
}

React Rendering and Update Source Code

Rendering Process Analysis

From createElement to Fiber Tree:

// ReactElement.js
function createElement(type, config, children) {
  return ReactElement(
    type,
    key,
    ref,
    self,
    source,
    ReactCurrentOwner.current,
    props,
  )
}

// ReactFiber.old.js
function createFiberFromElement(element) {
  const owner = element._owner
  const fiber = new FiberNode(
    element.type === REACT_ELEMENT_TYPE ? element.type : null,
    element.key,
    element.ref,
    NoMode,
  )
  fiber.elementType = element.type
  fiber.type = element.type
  fiber.pendingProps = element.props
  fiber._debugOwner = owner
  return fiber
}

Commit Phase:

// ReactFiberWorkLoop.old.js
function commitRoot(root) {
  // Phase 1: Before mutation
  commitBeforeMutationEffects(root)

  // Phase 2: Mutation
  commitMutationEffects(root, renderPriorityLevel)

  // Phase 3: Layout
  commitLayoutEffects(root, expirationTime)
}

function commitMutationEffects(root, renderPriorityLevel) {
  // Perform DOM updates
  while (nextEffect !== null) {
    const fiber = nextEffect
    nextEffect = nextEffect.nextEffect

    switch (fiber.tag) {
      case FunctionComponent:
      case ForwardRef:
      case MemoComponent:
        // Skip function components
        break
      default:
        commitWork(fiber)
    }
  }
}

Update Mechanism Analysis

State Update Process:

// ReactFiberHooks.old.js
function updateReducer(reducer, initialArg, init) {
  const hook = updateWorkInProgressHook()
  const queue = hook.queue

  // Add new update to queue
  const action = update
  const update = {
    lane,
    action,
    eagerReducer: null,
    eagerState: null,
    next: null,
  }
  enqueueUpdate(fiber, update, lane)

  // Schedule update
  scheduleUpdateOnFiber(fiber, lane, eventTime)

  // Return current state
  return hook.memoizedState
}

// ReactFiberWorkLoop.old.js
function scheduleUpdateOnFiber(fiber, lane, eventTime) {
  // Mark Fiber that needs updating
  const root = markUpdateLaneFromFiberToRoot(fiber, lane)
  if (root === null) return

  // Schedule rendering
  ensureRootIsScheduled(root, eventTime)
}

Batch Update Implementation

unstable_batchedUpdates Source Code:

// ReactDefaultBatchingStrategy.old.js
let isBatchingUpdates = false
let isUnbatchingUpdates = false
let pendingUpdates = []

function batchedUpdates(callback, a, b, c, d, e) {
  if (isBatchingUpdates && !isUnbatchingUpdates) {
    // Already in batch, execute callback directly
    return callback(a, b, c, d, e)
  }

  // Start batching
  isBatchingUpdates = true
  try {
    return callback(a, b, c, d, e)
  } finally {
    // End batching, flush updates
    isBatchingUpdates = false
    flushPendingUpdates()
  }
}

function flushPendingUpdates() {
  const updates = pendingUpdates
  pendingUpdates = []

  // Process all pending component updates
  updates.forEach(update => {
    const { instance, partialState } = update
    instance.setState(partialState)
  })
}

Asynchronous Rendering Implementation

Scheduler Implementation:

// Scheduler.js
function scheduleCallback(priorityLevel, callback) {
  // Create task
  const task = {
    id: taskIdCounter++,
    callback,
    priorityLevel,
    startTime: currentTime(),
    expirationTime: currentTime() + timeoutForPriorityLevel(priorityLevel),
  }

  // Add to task queue
  push(taskQueue, task)

  // Request worker thread to execute tasks
  requestHostCallback(flushWork)
}

function flushWork(hasTimeRemaining, initialTime) {
  // Execute highest priority tasks
  while (taskQueue.length > 0) {
    const currentTime = getCurrentTime()
    const task = peek(taskQueue)

    if (task.expirationTime > currentTime) {
      // Time slice exhausted, pause scheduling
      return true
    }

    // Execute task
    const callback = task.callback
    if (typeof callback === 'function') {
      callback()
    }

    // Remove completed task
    pop(taskQueue)
  }

  return false
}

Lane Model Implementation:

// ReactFiberLane.old.js
export function requestUpdateLane(fiber) {
  // Return priority Lane based on component type and interaction
  if (fiber.mode & ConcurrentMode) {
    if (isEventHandle(fiber)) {
      return InputContinuousLane
    }
    if (fiber.memoizedState !== null) {
      // Stateful components use default priority
      return DefaultLane
    }
    return TransitionLane
  }
  return SyncLane
}

export function scheduleUpdateOnFiber(fiber, lane, eventTime) {
  // Mark Fiber that needs updating
  const root = markUpdateLaneFromFiberToRoot(fiber, lane)
  if (root === null) return

  // Schedule rendering
  ensureRootIsScheduled(root, lane, eventTime)
}

Server-Side Rendering Source Code

Next.js Core Rendering Logic:

// packages/next/server/render.tsx
async function renderToHTML(
  req,
  res,
  pathname,
  query,
  renderOpts,
) {
  // 1. Create React app instance
  const app = <App {...renderOpts} />

  // 2. Collect required page data
  const data = await getStaticPropsData(pathname)

  // 3. Perform React rendering
  const html = ReactDOMServer.renderToString(
    <AppContext.Provider value={appContext}>
      <App {...renderOpts} data={data} />
    </AppContext.Provider>
  )

  // 4. Inject initial state
  const finalHtml = `
    <!DOCTYPE html>
    <html>
      <head>${renderOpts.head}</head>
      <body>
        <div id="__next">${html}</div>
        <script>
          window.__NEXT_DATA__ = ${serialize(data)}
        </script>
      </body>
    </html>
  `

  return finalHtml
}

Streaming SSR Implementation:

// React 18 streaming rendering
function renderToPipeableStream(
  element,
  options,
) {
  return new PipeableStream({
    onShellReady() {
      // Triggered when root component rendering is complete
      res.setHeader('Content-type', 'text/html')
      stream.pipe(res)
    },
    onShellError(error) {
      // Handle rendering errors
      console.error('Shell rendering error:', error)
      res.statusCode = 500
      res.end('Internal Server Error')
    },
    onError(error) {
      // Handle child component errors
      console.error('Streaming rendering error:', error)
    }
  })
}

React Performance Optimization Source Code

Fiber Priority Scheduling Source Code

Priority Comparison Logic:

// ReactFiberLane.old.js
export function higherPriorityLane(a, b) {
  return a !== NoLane && (a & CommonLanes) >= (b & CommonLanes)
}

export function mergeLanes(a, b) {
  return a | b
}

export function laneToName(lane) {
  switch (lane) {
    case SyncLane:
      return 'Sync'
    case InputContinuousLane:
      return 'InputContinuous'
    case DefaultLane:
      return 'Default'
    // ...other priorities
  }
}

Scheduling Priority Handling:

// ReactFiberWorkLoop.old.js
function performConcurrentWorkOnRoot(root) {
  // Get the highest priority Lane
  const lane = selectHighestPriorityLane(root.pendingLanes)

  // Execute work loop
  workLoopConcurrent()

  // Check for interruption
  if (shouldYield()) {
    // Pause rendering to allow browser to handle high-priority tasks
    return null
  }

  // Complete current frame work
  completeUnitOfWork(workInProgress)
}

Diff Algorithm Optimization Source Code

Keyed Reconciliation Optimization:

// ReactChildFiber.old.js
function reconcileChildrenArray(
  returnFiber,
  currentFirstChild,
  newChildren,
  lanes,
) {
  // ...previous code

  // Fast path: If old and new child nodes are identical
  if (oldFiber !== null && newIdx < newChildren.length) {
    const prevChild = oldFiber
    const newChild = newChildren[newIdx]

    if (prevChild.key === newChild.key) {
      // Reuse Fiber node
      const existing = useFiber(prevChild, newChild.props)
      existing.return = returnFiber
      return existing
    }
  }

  // ...subsequent code
}

Component Type Optimization:

// ReactFiberBeginWork.old.js
function beginWork(
  current,
  workInProgress,
  renderLanes,
) {
  switch (workInProgress.tag) {
    case HostRoot:
      return updateHostRoot(current, workInProgress, renderLanes)
    case HostComponent:
      return updateHostComponent(current, workInProgress, renderLanes)
    case FunctionComponent:
      return updateFunctionComponent(current, workInProgress, renderLanes)
    // ...other component types
  }
}

// Reuse Fiber node for same-type components
function updateHostComponent(
  current,
  workInProgress,
  renderLanes,
) {
  if (current.type === workInProgress.type) {
    // Reuse DOM node
    workInProgress.stateNode = current.stateNode
    // Update props
    cloneUpdateQueue(current, workInProgress)
    return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes)
  }

  // Different type, create new node
  return mountHostComponent(current, workInProgress, renderLanes)
}

Hooks Dependency Optimization Source Code

Dependency Array Comparison:

// ReactFiberHooks.old.js
function updateEffectImpl(fiberFlags, hookFlags, create, deps) {
  const hook = updateWorkInProgressHook()
  const nextDeps = deps === undefined ? null : deps

  if (currentHook !== null) {
    const prevEffect = currentHook.memoizedState
    if (nextDeps !== null) {
      const prevDeps = prevEffect.deps
      if (areHookInputsEqual(nextDeps, prevDeps)) {
        // Dependencies unchanged, skip effect
        hook.memoizedState = pushEffect(hookFlags, create, deps)
        return
      }
    }
  }

  // Dependencies changed, execute effect
  currentlyRenderingFiber.flags |= fiberFlags
  hook.memoizedState = pushEffect(HasEffect | hookFlags, create, deps)
}

useMemo Cache Optimization:

// ReactFiberHooks.old.js
function updateMemo(nextCreate, deps) {
  const hook = updateWorkInProgressHook()
  const nextDeps = deps === undefined ? null : deps

  if (currentHook !== null) {
    const prevEffect = currentHook.memoizedState
    if (nextDeps !== null) {
      const prevDeps = prevEffect[1]
      if (areHookInputsEqual(nextDeps, prevDeps)) {
        // Dependencies unchanged, return cached value
        return prevEffect[0]
      }
    }
  }

  // Dependencies changed, recompute
  const nextValue = nextCreate()
  hook.memoizedState = [nextValue, nextDeps]
  return nextValue
}

Event System Optimization Source Code

Event Delegation Optimization:

// ReactEventListener.js
const simpleEventPluginEventTypes = {
  click: {
    registrationName: 'onClick',
    dependencies: ['click'],
  },
  // ...other event types
}

function registerSimpleEvents() {
  for (const topLevelType in simpleEventPluginEventTypes) {
    const eventType = simpleEventPluginEventTypes[topLevelType]
    listenToNativeEvent(
      topLevelType,
      document, // All events delegated to document
      eventType.dependencies[0],
    )
  }
}

Event Pool Optimization:

// ReactSyntheticEvent.js
let eventPool = []

function getPooledEvent(dispatchConfig, targetInst, nativeEvent) {
  if (eventPool.length) {
    const instance = eventPool.pop()
    instance.constructor.call(instance, dispatchConfig, targetInst, nativeEvent)
    return instance
  }
  return new SyntheticEvent(dispatchConfig, targetInst, nativeEvent)
}

function releasePooledEvent(event) {
  event.destructor()
  eventPool.push(event)
}

Code Splitting Source Code

React.lazy Implementation:

// react/src/ReactLazy.js
function lazy<T, R>(ctor: () => Thenable<T, R>): LazyComponent<T> {
  let result
  let thenable
  let error

  const lazyType = {
    $$typeof: REACT_LAZY_TYPE,
    _status: -1,
    _result: null,

    read() {
      if (this._status === -1) {
        // First access, start loading
        if (typeof ctor !== 'function') {
          throw new Error('lazy() expects a function')
        }

        thenable = ctor()
        thenable.then(
          module => {
            this._status = 1
            this._result = module.default
          },
          error => {
            this._status = 2
            this._result = error
          }
        )
      } else if (this._status === 1) {
        // Loading complete
        return this._result
      } else {
        // Loading failed
        throw this._result
      }
    }
  }

  return lazyType
}

Suspense Implementation:

// ReactFiberSuspenseComponent.old.js
function suspenseStackCursor.read() {
  return readContext(SuspenseContext)
}

function throwException(
  root,
  returnFiber,
  sourceFiber,
  value,
  renderLanes,
) {
  // Check if it's a Suspense boundary
  const suspenseBoundary = findFirstSuspended(result)

  if (suspenseBoundary !== null) {
    // Pause rendering, show fallback
    suspenseBoundary.flags |= ShouldCapture
    workInProgress.flags |= DidCapture

    // Save incomplete work to Suspense boundary
    suspenseBoundary.updateQueue = {
      baseState: null,
      firstBaseUpdate: null,
      lastBaseUpdate: null,
      shared: {
        pending: null,
      },
      effects: null,
    }

    // Return Suspense fallback
    return createFiberFromSuspenseFallback(suspenseBoundary)
  }

  // No Suspense boundary, throw error
  throw value
}
Share your love