createRoot
创建 React 根节点 - React 18+ 的标准应用启动方式
核心概述
createRoot 是 React 18 引入的新 API,用于创建 React 根节点并渲染应用。 它取代了 React 17 的 render 方法,启用并发渲染 (Concurrent Rendering)、 自动批处理 (Automatic Batching) 等新特性。
核心特性:
- 启用并发渲染模式 (Concurrent Rendering)
- 支持 Suspense 和流式 SSR
- 自动批处理更新 (Automatic Batching)
- 支持并发特性 (useTransition, useDeferredValue)
- 更好的错误恢复机制
✅ React 18+ 推荐使用
所有新项目应该使用 createRoot。 旧项目也应该尽快迁移,以充分利用 React 18 的新特性。
技术规格
导入方式
TypeScript
import { createRoot } from 'react-dom/client';函数签名
TypeScript
function createRoot(
container: Element | DocumentFragment,
options?: {
onRecoverableError?: (error: Error) => void;
identifierPrefix?: string;
}
): RootRoot 对象方法
TypeScript
interface Root {
render(children: ReactNode): void;
unmount(): void;
}参数说明
| 参数 | 类型 | 说明 |
|---|---|---|
container | Element | DOM 元素,通常是 document.getElementById('root') |
options.onRecoverableError | (error) => void | 可恢复错误的回调 |
实战演练
1. 基础用法
TypeScript
import { createRoot } from 'react-dom/client';
import App from './App';
// 获取 DOM 容器
const container = document.getElementById('root');
// 创建根节点
const root = createRoot(container);
// 渲染应用
root.render(<App />);2. 完整的应用启动
TypeScript
import { createRoot } from 'react-dom/client';
import App from './App';
import './index.css';
const container = document.getElementById('root');
if (!container) {
throw new Error('Failed to find the root element');
}
const root = createRoot(container, {
onRecoverableError(error) {
console.error('Recoverable error:', error);
// 可以发送到错误监控服务
// logErrorToService(error);
},
});
root.render(<App />);
// Hot Module Replacement (开发环境)
if (module.hot) {
module.hot.accept('./App', () => {
const NextApp = require('./App').default;
root.render(<NextApp />);
});
}3. 从 React 17 迁移
TypeScript
// ❌ React 17 及之前 (已弃用)
import { render } from 'react-dom';
import App from './App';
render(<App />, document.getElementById('root'));
// ✅ React 18+ (推荐)
import { createRoot } from 'react-dom/client';
import App from './App';
const root = createRoot(document.getElementById('root'));
root.render(<App />);API 对比:React 17 vs React 18
| 特性 | React 17 (render) | React 18 (createRoot) |
|---|---|---|
| 并发渲染 | ❌ | ✅ |
| 自动批处理 | ❌ | ✅ |
| Suspense 支持 | ⚠️ 有限 | ✅ 完整 |
| 流式 SSR | ❌ | ✅ |
| 并发特性 | ❌ | ✅ |
| 错误恢复 | 基础 | 增强 |