
## React 19 实战指南:use() Hook、Actions 与全新 Hooks 深度解析
React 19 正式发布已有数月,带来了许多令人兴奋的新特性。本文聚焦三个最具实践价值的更新,通过真实代码示例帮你快速上手。
### 一、use() Hook:同步风格的异步数据读取
React 19 新增的 `use()` Hook 让你可以在组件渲染函数中直接读取 Promise 或 Context,不再需要在顶层调用 Hook 的严格限制。
**读取 Context 示例:**
```jsx import { use } from 'react';
function ThemeButton() { // 在条件语句中使用 Hook —— React 19 允许! const theme = use(ThemeContext);
return 点击我; } ```
**读取 Promise(支持 Suspense):**
```jsx function UserProfile({ userIdPromise }) { const userId = use(userIdPromise); const data = use(fetchUserData(userId));
return
{data.name} - {data.email}
; }
// 父组件传入 Promise function App() { return ( }> ); } ```
`use()` 最大的价值在于:它彻底打破了"Hooks 必须在顶层调用"的铁律,你可以在条件、循环甚至提前 return 之后使用它。
### 二、Actions:表单交互的范式升级
React 19 引入的 Actions 机制,让表单提交变得前所未有的简单。`useActionState` 替代了繁琐的 `useState` + 手动提交逻辑。
```jsx import { useActionState } from 'react';
async function submitFeedback(prevState, formData) { const name = formData.get('name'); const message = formData.get('message');
// 模拟 API 调用 await new Promise(r => setTimeout(r, 1000));
if (!name) return { error: '请填写姓名' }; return { success: true, data: { name, message } }; }
function FeedbackForm() { const [state, formAction, isPending] = useActionState(submitFeedback, null);
return (