2026-04-21 10:55:49
React并发模式源码分析
React并发模式是React 18引入的一项重大特性,旨在通过异步渲染和任务调度提升应用的性能和用户体验。以下是对其源码实现的详细分析,包括Fiber架构、Scheduler、Lane模型和并发特性(如useTransition)。
1. 并发模式简介什么是并发模式?
并发模式(Concurrent Mode)是React的一种渲染策略,允许React在渲染过程中中断和恢复任务,从而优先处理紧急更新(如用户交互),而将非紧急任务(如数据加载)推迟到浏览器空闲时执行。它基于Fiber架构,利用时间分片(Time Slicing)和优先级调度实现。
示例场景
用户在输入框快速输入时,React优先更新输入框内容。同时,后台可能在渲染大数据列表,并发模式确保输入不卡顿。
核心目标
关键特性
示例:启用并发模式
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));}并发模式的主渲染函数:
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); }}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如何在底层优化渲染性能。