React篇:React并发模式源码分析

React篇:React并发模式源码分析
最新回答
杯别

2026-04-21 10:55:49

React并发模式源码分析

React并发模式是React 18引入的一项重大特性,旨在通过异步渲染和任务调度提升应用的性能和用户体验。以下是对其源码实现的详细分析,包括Fiber架构、Scheduler、Lane模型和并发特性(如useTransition)。

1. 并发模式简介

什么是并发模式?

并发模式(Concurrent Mode)是React的一种渲染策略,允许React在渲染过程中中断和恢复任务,从而优先处理紧急更新(如用户交互),而将非紧急任务(如数据加载)推迟到浏览器空闲时执行。它基于Fiber架构,利用时间分片(Time Slicing)和优先级调度实现。

示例场景

用户在输入框快速输入时,React优先更新输入框内容。同时,后台可能在渲染大数据列表,并发模式确保输入不卡顿。

核心目标

  • 响应性:确保高优先级任务(如用户事件)快速响应。
  • 平滑性:避免阻塞主线程,提供流畅的UI更新。
  • 灵活性:支持动态调整任务优先级。

关键特性

  • 时间分片:将长任务拆分为小块。
  • 优先级调度:通过Scheduler和Lane模型管理任务。
  • 异步渲染:支持中断和恢复渲染。

示例:启用并发模式

import { createRoot } from 'react-dom/client';const root = createRoot(document.getElementById('root'), { concurrent: true });root.render(<App />);2. 并发模式的核心原理Fiber架构的基础

并发模式依赖Fiber架构,每个组件对应一个Fiber节点。Fiber将渲染分解为可中断的工作单元(Work),支持暂停和恢复。

Fiber节点结构

const fiber = { tag: FunctionComponent, // 组件类型 type: App, // 组件函数 memoizedState: null, // 状态 updateQueue: null, // 更新队列 child: null, // 子Fiber sibling: null, // 兄弟Fiber return: null, // 父Fiber lanes: NoLanes, // 优先级轨道 effectTag: NoEffect // 副作用标记};Lane模型:优先级管理

Lane模型是并发模式的核心机制,用32位整数表示任务优先级,每个位(Lane)代表一种优先级状态。

Lane定义

// react-reconciler/src/ReactFiberLane.jsconst NoLanes = 0b0000000000000000000000000000000;const SyncLane = 0b0000000000000000000000000000001; // 同步const InputContinuousLane = 0b0000000000000000000000000010; // 用户交互const DefaultLane = 0b0000000000000000000000000100; // 默认const TransitionLane = 0b0000000000000000000000010000; // 过渡const IdleLane = 0b0100000000000000000000000000000; // 空闲

位运算:通过&、|操作管理多个优先级。

优先级排序:低位优先级高于高位。

时间分片与调度

Scheduler模块(scheduler包)负责将任务分片并调度到浏览器空闲时间,利用MessageChannel或requestIdleCallback实现。

示例:分片渲染

function workLoop(hasTimeRemaining) { while (workInProgress !== null && hasTimeRemaining()) { workInProgress = performUnitOfWork(workInProgress); }}3. 并发模式的源码解析

以下基于React 18的源码(react-reconciler和scheduler),逐步分析并发模式的实现。

渲染入口:scheduleUpdateOnFiber

并发渲染从scheduleUpdateOnFiber开始:

// react-reconciler/src/ReactFiberWorkLoop.jsfunction scheduleUpdateOnFiber(fiber, lane) { markRootUpdated(fiberRoot, lane); // 标记优先级 ensureRootIsScheduled(fiberRoot); // 调度}function markRootUpdated(root, lane) { root.pendingLanes |= lane; // 更新待处理Lane}function ensureRootIsScheduled(root) { const highestLane = getHighestPriorityLane(root.pendingLanes); if (highestLane === NoLane) return; const priority = laneToSchedulerPriority(highestLane); scheduleCallback(priority, () => performConcurrentWorkOnRoot(root, highestLane));}
  • pendingLanes:记录所有待处理的优先级。
  • scheduleCallback:调用Scheduler调度任务。
并发渲染循环:performConcurrentWorkOnRoot

并发模式的主渲染函数:

function performConcurrentWorkOnRoot(root, lane) { renderRootConcurrent(root, lane); // 并发渲染 const finishedWork = root.current.alternate; root.finishedWork = finishedWork; root.finishedLanes = lane; commitRoot(root); // 提交}function renderRootConcurrent(root, lanes) { do { try { workLoopConcurrent(); break; } catch (error) { handleError(root, error); } } while (true);}function workLoopConcurrent() { while (workInProgress !== null && !shouldYield()) { workInProgress = performUnitOfWork(workInProgress); }}
  • shouldYield:由Scheduler提供,检查是否需要中断。
Scheduler的实现

Scheduler(scheduler/src/Scheduler.js)驱动时间分片:

function scheduleCallback(priorityLevel, callback) { const task = { callback, priorityLevel, expirationTime: getCurrentTime() + timeoutFromPriority(priorityLevel) }; push(taskQueue, task); requestHostCallback(flushWork);}function flushWork(hasTimeRemaining) { while (peek(taskQueue) !== null && hasTimeRemaining()) { const task = pop(taskQueue); task.callback(); }}function shouldYieldToHost() { return getCurrentTime() - frameStartTime >= yieldInterval; // 默认5ms}4. 总结

React并发模式通过Fiber架构、Lane模型和Scheduler实现了异步渲染和任务调度,从而在高负载场景下保持应用的响应性和平滑性。其核心在于将渲染任务分解为可中断的小块,并根据优先级动态调整执行顺序。通过深入分析其源码实现,可以更好地理解React如何在底层优化渲染性能。