看看 React Compiler 对你的组件做了些什么

2025年11月15日Elecmonkey

做了一个小工具:See React Compiler

在线体验

一个例子

原始代码:

jsx
1import React, { useState } from 'react'; 2 3export const Demo = () => { 4 const [count, setCount] = useState(0); 5 return <button onClick={() => setCount(count + 1)}>Count: {count}</button>; 6};

编译后:

jsx
1import { c as _c } from "react/compiler-runtime"; 2import React, { useState } from 'react'; 3 4export const Demo = () => { 5 const $ = _c(6); 6 if ($[0] !== "c8ddead80551c9ffa196048aad479d7c4518a54bc7192e6ca422a973a27883f7") { 7 for (let $i = 0; $i < 6; $i += 1) { 8 $[$i] = Symbol.for("react.memo_cache_sentinel"); 9 } 10 $[0] = "c8ddead80551c9ffa196048aad479d7c4518a54bc7192e6ca422a973a27883f7"; 11 } 12 const [count, setCount] = useState(0); 13 let t0; 14 if ($[1] !== count) { 15 t0 = () => setCount(count + 1); 16 $[1] = count; 17 $[2] = t0; 18 } else { 19 t0 = $[2]; 20 } 21 let t1; 22 if ($[3] !== count || $[4] !== t0) { 23 t1 = <button onClick={t0}>Count: {count}</button>; 24 $[3] = count; 25 $[4] = t0; 26 $[5] = t1; 27 } else { 28 t1 = $[5]; 29 } 30 return t1; 31};

编译器做了什么?

  1. 创建缓存数组 - 存储中间结果和依赖
  2. 缓存 onClick 函数 - 只在 count 变化时重新创建(相当于 useCallback
  3. 缓存 JSX 元素 - 只在依赖变化时重新创建(相当于 useMemo