簡介
React 19 代表了前端開發的重大典範轉移。
先前僅限於 Next.js 等元框架的功能(例如用於表單處理的 React Server Components (RSC) 和 Actions API)現在已正式整合到穩定的核心 React 庫中。
本指南重點介紹了 React 19 中最重要的功能,提供了實用的程式碼範例和升級技巧來清理您的程式碼庫。
1. 使用 Actions API 簡化非同步狀態
React 19 中的一個突出功能是引入 Actions,旨在簡化管理非同步突變、載入器覆蓋和表單提交。
從歷史上看,追蹤非同步請求需要手動聲明待處理狀態(“isPending”)、成功標誌和錯誤回應。 React 19 使用標準鉤子自動處理這些狀態。
使用 useActionState 提交表單
import { useActionState } from 'react';
// Async form action handler
async function updateProfile(prevState, queryData) {
try {
await api.post("/profile", queryData);
return { success: true, message: "Profile saved successfully!" };
} catch (err) {
return { success: false, message: err.message };
}
}
function ProfileForm() {
// state: return value from the action
// formAction: handler passed to the HTML form action attribute
// isPending: boolean tracking if the async action is currently executing
const [state, formAction, isPending] = useActionState(updateProfile, null);
return (
<form action={formAction}>
<input type="text" name="username" required />
<button type="submit" disabled={isPending}>
{isPending ? "Saving..." : "Save"}
</button>
{state && <p>{state.message}</p>}
</form>
);
}
useActionState(以前在測試階段稱為useFormState)將非同步處理程序直接連結到本機表單屬性,自動管理載入指示器。
使用 useOptimistic 進行樂觀更新
對於聊天發送或「喜歡」按鈕等互動操作,React 19 引入了 useOptimistic。這允許您在伺服器請求完成之前立即更新 UI,並在請求失敗時使用內建回滾功能。
2. 透過新的 use API 進行資源解析
React 19 引入了 use,這是一個新的類似鉤子的 API,旨在解析 Promises 並在渲染期間動態讀取 Context 值。
與標準 React 掛鉤(如“useEffect”或“useContext”)不同,“use”可以有條件地(在“if”語句內)和循環內調用。
使用「Suspense」解決渲染中的 Promise
@@@代碼區塊1@@@
- 當您將 Promise 傳遞給
useAPI 時,React 會暫停渲染直到 Promise 解析,將載入狀態委託給最近的<Suspense>包裝器。
3. ref 為標準 Prop(棄用forwardRef)
React 19 中一個令人歡迎的生活品質變化是簡化了子元件的引用傳遞 (refs)。
以前,將“ref”向下傳遞給子元素需要將組件包裝在“forwardRef()”中,這會添加不必要的樣板。在 React 19 中,「ref」被視為標準屬性。
簡化的引用語法
// No forwardRef needed! Access 'ref' directly from props
function MyInput({ label, ref }) {
return (
<label>
{label}
<input ref={ref} />
</label>
);
}
// Parent rendering usage remains identical
function Parent() {
const inputRef = useRef(null);
return <MyInput label="Username" ref={inputRef} />;
}
4. 明確客戶端與伺服器環境的界限
隨著伺服器元件整合到庫核心中,文件層級的環境執行規則聲明現已標準化:
"use client": 標記在瀏覽器中執行並使用useState或useEffect等客戶端功能的元件。"use server": 標記在伺服器上執行的函數(伺服器操作),防止敏感憑證或資料庫查詢洩漏給客戶端。
結論
React 19 透過自動化非同步突變、簡化引用和引入原生 Promise 解析來消除樣板程式碼。
棄用「forwardRef」並採用「useActionState」是清理元件程式碼庫的絕佳機會。請參閱官方 React 19 升級指南來規劃您的過渡。

