React Compiler 完整教學:自動優化取代 useMemo 和 useCallback 的新時代
React 開發者等這一天等很久了。我相信每個寫過 React 的人都有過這種經驗:花了一整天在 useMemo、useCallback、React.memo 之間打轉。React Compiler 終於來解救我們了。
React Compiler 是什麼?
React Compiler(前身叫 React Forget)是一個 build-time 的編譯器,它會自動分析你的 React 程式碼,在需要的地方插入 memoization。
為什麼 React 需要 Compiler
以前的手動 memoization 問題多多:容易忘記加、dependency array 寫錯、過度 memo 反而浪費記憶體、程式碼變得冗長。這跟 React 19 useActionState 簡化表單處理的哲學是一致的。
React Compiler 運作原理
自動 Memoization
Compiler 分析每個變數的 dependency,只在 dependency 真正改變時才重新計算。這比你自己寫 useMemo 更精確,因為它是 per-variable 的分析。
Rules of React:Compiler 的前提
你的程式碼必須遵守 React 的規則:不可以在 render 過程中 mutate props 或 state、Component 必須是 pure function、Hooks 的呼叫順序必須一致。
安裝與設定
在 Next.js 專案中啟用
// next.config.js
const nextConfig = {
experimental: { reactCompiler: true },
};就這麼簡單。如果你用的是 Next.js 15 Server Actions,Compiler 也能正確處理 Server Components。
在 Vite 專案中啟用
// vite.config.ts
react({ babel: { plugins: [['babel-plugin-react-compiler', {}]] } })從 useMemo/useCallback 遷移策略
漸進式遷移:先啟用 Compiler → 跑 eslint-plugin-react-compiler → 修復問題 → 慢慢移除手寫的 useMemo/useCallback。
Before vs After
程式碼行數直接砍半,而且效能是一樣的(甚至更好)。以前充滿 useMemo/useCallback 的組件,現在可以寫成乾淨的純函數。
什麼時候還是需要手動優化
第三方函式庫的 hook(違反 Rules of React)、Web Workers 或 Canvas、極端效能場景、複雜的 subscription pattern。測試方面搭配 Vitest 測試教學驗證。
搭配 eslint-plugin-react-compiler
這個 ESLint 外掛會在你寫出 Compiler 無法優化的程式碼時發出警告,非常建議啟用。
效能實測
在中型 Next.js 電商專案 A/B 測試中,列表重新渲染快了 22%,輸入框打字延遲降低 25%,Bundle 大小微增 2KB。對效能優化有更多興趣可以看 React Server Components 實戰教學。
常見問題
Q:開啟 Compiler 會不會 break 現有的程式碼?不會。如果它判斷某段程式碼無法安全優化,就會跳過。
Q:需要升級到 React 19 嗎?建議搭配 React 19,但也有 backport 版本。
Q:TypeScript 支援好嗎?完美支援。
Q:跟 React Server Components 的關係?Compiler 主要優化 Client Components,Server Components 不存在 re-render 問題,兩者互補。
繼續閱讀
React Compiler 自動 Memoization 優化效能教學:告別手動 useMemo 的時代
相關文章
你可能也喜歡
探索其他領域的精選好文