React 19 带来了什么?
React 19 是 React 历史上最重要的版本之一,引入了全新的并发特性和开发体验改进。
Actions — 异步状态管理新范式
在 React 19 之前,处理异步操作需要手动管理 loading、error 等状态。Actions 将这一切自动化:
function UpdateName() {
const [error, submitAction, isPending] = useActionState(
async (prevState, formData) => {
const error = await updateName(formData.get("name"));
if (error) return error;
redirect("/path");
return null;
},
null,
);
return (
<form action={submitAction}>
<input type="text" name="name" />
<button disabled={isPending}>Update</button>
{error && <p>{error}</p>}
</form>
);
}
use() Hook — 在渲染中读取资源
新的 use() API 允许你在渲染阶段直接读取 Promise 或 Context:
import { use } from 'react';
function Comments({ commentsPromise }) {
// use() will suspend until the promise resolves
const comments = use(commentsPromise);
return comments.map(comment => <p key={comment.id}>{comment}</p>);
}
新的 Ref 传递方式
函数组件现在可以直接接受 ref 作为 prop,无需 forwardRef:
function MyInput({ placeholder, ref }) {
return <input placeholder={placeholder} ref={ref} />
}
// 使用
<MyInput ref={ref} />
Document Metadata 支持
可以在组件中直接渲染 、 等标签:
function BlogPost({ post }) {
return (
<article>
<h1>{post.title}</h1>
<title>{post.title}</title>
<meta name="author" content="Author Name" />
<p>{post.content}</p>
</article>
);
}
升级建议
React 19 的升级相对平滑,官方提供了 codemod 工具帮助自动迁移。建议先在非关键路径试验新特性,逐步推广到整个项目。
总结
React 19 标志着 React 开发体验的重大飞跃,Actions、use()、Server Components 的成熟让全栈 React 开发变得更加优雅高效。