如何实现react时间切片
React 时间切片实现方法
React 时间切片(Time Slicing)是通过将渲染任务分解为小块并在浏览器空闲时执行,以避免长时间任务阻塞主线程。以下是实现方法:
使用 React 的 Concurrent Mode
启用 Concurrent Mode 是使用时间切片的前提。在 React 18 及以上版本中,可以通过以下方式启用:

import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
使用 useTransition 或 startTransition
useTransition 和 startTransition 允许将非紧急更新标记为可中断,从而让出主线程给高优先级任务:
import { useTransition } from 'react';
function App() {
const [isPending, startTransition] = useTransition();
const handleClick = () => {
startTransition(() => {
// 非紧急状态更新
setState(newState);
});
};
return (
<button onClick={handleClick}>
{isPending ? 'Loading...' : 'Click Me'}
</button>
);
}
使用 Suspense 配合懒加载
通过 Suspense 和 React.lazy 可以将组件加载拆分为可中断的任务块:

const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
手动控制任务分片
对于复杂任务,可以手动将任务分解为小块,并使用 requestIdleCallback 或 setTimeout 调度:
function processChunk(data, chunkSize, callback) {
let index = 0;
function nextChunk() {
const chunk = data.slice(index, index + chunkSize);
callback(chunk);
index += chunkSize;
if (index < data.length) {
requestIdleCallback(nextChunk);
}
}
requestIdleCallback(nextChunk);
}
优化长列表渲染
对于长列表,使用 react-window 或 react-virtualized 仅渲染可视区域内容:
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
function App() {
return (
<List
height={600}
itemCount={1000}
itemSize={35}
width={300}
>
{Row}
</List>
);
}
关键注意事项
- Concurrent Mode 需要 React 18 及以上版本
- 时间切片不改变最终渲染结果,只优化渲染过程
- 避免在时间切片任务中执行同步 DOM 操作
- 测试不同设备的性能表现,调整分片大小






