React Hooks 的规则:为什么 Hook 不能写在条件语句里
版本以 React 19.3.1 为准。
概念
Hook 是在函数组件或自定义 Hook 的顶层调用、以 use 开头的函数,用来把状态、副作用、引用等能力挂到组件实例上。组件函数本身没有实例,每次渲染都是一次普通的函数调用;状态之所以能跨渲染保留,是因为 React 把它存在组件对应的 Fiber 上。
官方规定的两条规则(Rules of Hooks):
- 只在顶层调用 Hook:不放在条件、循环、嵌套函数、
try/catch/finally里,也不放在提前return之后。 - 只在 React 函数组件或自定义 Hook 中调用 Hook,不在普通 JavaScript 函数、类组件、事件处理函数中调用。
use 是例外:它可以在条件和循环中调用,但仍然只能在组件或 Hook 里调用。
几个相关 API:
| API | 存什么 | 修改后是否重新渲染 |
|---|---|---|
useState | 决定界面的数据 | 是 |
useRef | 一个 { current } 对象,整个组件生命周期内是同一个对象 | 否 |
useId | 当前组件实例唯一、跨渲染稳定的字符串 | 不涉及 |
| 自定义 Hook | 一段组合了其他 Hook 的逻辑 | 取决于内部用了什么 |
底层机制:Hook 链表按顺序对号入座
Fiber 上的 Hook 单向链表
函数组件 Fiber 的 memoizedState 字段指向一条 Hook 链表,每调用一次 Hook,就占用链表上的一个节点:
1
2
3
4
5
6
7
8
// mountWorkInProgressHook,19.3.1 开发构建第 8192 行
function mountWorkInProgressHook() {
var hook = { memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null };
null === workInProgressHook
? (currentlyRenderingFiber.memoizedState = workInProgressHook = hook) // 第一个 Hook
: (workInProgressHook = workInProgressHook.next = hook); // 接在上一个后面
return workInProgressHook;
}
不同 Hook 在节点的 memoizedState 里存不同东西。实验 1 在 jsdom 中通过 DOM 节点上的 __reactFiber$ 私有属性拿到组件 Fiber,遍历它的 Hook 链表:
1
2
3
4
5
6
7
8
function Probe() {
const [n] = useState(42);
const ref = useRef("ref-value");
const doubled = useMemo(() => n * 2, [n]);
useEffect(() => {}, [n]);
const id = useId();
return h("p", { id }, `${n}/${ref.current}/${doubled}`);
}
1
2
3
4
5
6
7
Probe fiber: tag=0 type=Probe key=null, child.type=p, sibling=null, return.tag=3, alternate=null
hook[0] memoizedState=42 queue=有 next=→
hook[1] memoizedState={current:"ref-value"} queue=null next=→
hook[2] memoizedState=[84,[42]] queue=null next=→
hook[3] memoizedState=effect{tag:9, deps:[42]} queue=null next=→
hook[4] memoizedState="_r_0_" queue=null next=null
updateQueue 中的 effect 链表 lastEffect.tag = 9
| Hook | 节点中的 memoizedState | 其他字段 |
|---|---|---|
useState / useReducer | 当前状态值 | queue 是更新队列,见《React 状态更新:为什么 setState 后马上读到的还是旧值》 |
useRef | { current } 对象本身 | 无 |
useMemo / useCallback | [值, 依赖数组] | 无 |
useEffect / useLayoutEffect | Effect 对象 { tag, create, deps, inst, next } | 同一个 Effect 对象还串在 Fiber 的 updateQueue.lastEffect 环形链表里,tag 9 表示「被动 Effect + 本次需要执行」 |
useId | 生成的 ID 字符串 | 无 |
链表节点上没有记录「这是哪个 Hook」或者「它叫什么名字」。React 只靠调用顺序区分它们:第一次调用的 Hook 对应第一个节点,第二次调用对应第二个节点。
mount 与 update 两套实现
renderWithHooks 在调用组件函数前设置当前的 dispatcher(ReactSharedInternals.H)。dispatcher 是一个对象,里面放着 useState、useEffect 等 Hook 的具体实现;组件里调用的 useState 只是转发给当前 dispatcher 上的同名函数:
- Fiber 第一次渲染(没有 current 树上的对应节点):用
HooksDispatcherOnMount,每个 Hook 调用mountWorkInProgressHook新建节点。 - 之后的渲染:用
HooksDispatcherOnUpdate,每个 Hook 调用updateWorkInProgressHook,沿着 current 树 Fiber 的旧链表前进一步,复制出新节点:
1
2
3
4
5
6
7
// updateWorkInProgressHook,19.3.1 开发构建第 8205 行(节选)
nextCurrentHook = currentHook === null
? currentlyRenderingFiber.alternate.memoizedState // 旧链表的第一个
: currentHook.next; // 旧链表的下一个
if (nextCurrentHook === null)
throw Error("Rendered more hooks than during the previous render.");
// 复制 memoizedState、baseState、baseQueue、queue 到新节点,接到新链表末尾
组件函数执行完后,finishRenderingHooks 检查旧链表是否正好走完;如果还剩节点,说明这次调用的 Hook 比上次少,抛出 Rendered fewer hooks than expected. This may be caused by an accidental early return statement.。随后它把 dispatcher 换成 ContextOnlyDispatcher,其中 useState、useEffect 等都指向 throwInvalidHookError,所以渲染结束后在别处调用 Hook 会抛出 Invalid hook call。
顺序被打乱时的三种结果
根据上面的实现,可以推出违反规则时的行为,实验 2 逐一验证:
- Hook 数量变多:旧链表先走完,
updateWorkInProgressHook抛错Rendered more hooks than during the previous render.,整棵树卸载(容器内容变成空字符串)。 - Hook 数量变少:
finishRenderingHooks抛错Rendered fewer hooks than expected.。 - 数量不变、顺序变了:每个 Hook 仍能拿到一个节点,只是拿错了。如果两个 Hook 类型不同(
useState拿到了useRef的节点,没有queue),会抛出Should have a queue.;如果类型相同(两个useState换了位置),React 没有任何办法发现,name拿到 28、age拿到「张三」,控制台零报错。
开发构建另外用一个数组记录每次渲染调用的 Hook 类型,前后不一致时先输出警告 React has detected a change in the order of Hooks called by ...。这个检查只比较类型,所以第 3 种中类型相同的调换不会触发警告。生产构建没有这些警告,错误信息被压缩成编号(实验 2:#310、#300、#311、#321)。
useRef 与 useId 的实现
mountRef 只做一件事:创建 { current: initialValue } 存进 Hook 节点,之后每次渲染返回同一个对象。
1
2
3
4
5
6
// mountRef,19.3.1 开发构建第 9010 行
function mountRef(initialValue) {
var hook = mountWorkInProgressHook();
initialValue = { current: initialValue };
return (hook.memoizedState = initialValue);
}
修改 ref.current 只是修改一个普通对象的属性,不经过更新队列,也不调用 scheduleUpdateOnFiber,所以不会触发渲染(实验 3)。
useId 只在挂载时生成 ID,存进 Hook 节点,之后的渲染直接返回旧值。生成方式有两种(mountId,19.3.1 开发构建第 9431 行):
- 纯客户端渲染:取模块级计数器
globalClientIdCounter++,格式为_r_<32 进制计数>_。实验 3 中的_r_0_、_r_1_就是这样来的。 - 水合(hydration):用组件在树中的位置(
treeContextId)编码,格式为_R_<位置编码>_。服务端按同样的树结构生成,所以两边一致。
ID 格式随版本变过:早期是 :r1:,19.1.0 改为 «r1»,19.2.0 改为现在的下划线形式。不要在代码里依赖具体格式。
解决的问题
类组件把状态放在实例的 this.state 上,复用带状态的逻辑要靠高阶组件或 render props,组件树会被一层层包装。Hook 让函数组件也能有状态,并把「一段带状态和副作用的逻辑」提取成普通函数复用:
1
2
3
4
5
6
7
8
9
10
11
12
13
function useOnlineStatus() {
const [online, setOnline] = useState(navigator.onLine);
useEffect(() => {
const update = () => setOnline(navigator.onLine);
window.addEventListener("online", update);
window.addEventListener("offline", update);
return () => {
window.removeEventListener("online", update);
window.removeEventListener("offline", update);
};
}, []);
return online;
}
调用顺序约定的代价是规则本身:React 不要求给 Hook 起名或传 key,换来的是调用必须稳定。官方 ESLint 插件 eslint-plugin-react-hooks 的 rules-of-hooks 规则在编译前检查这一点;运行时的检查只能覆盖一部分情况(见上一节第 3 种)。
适用场景
把条件放进 Hook 内部
1
2
3
4
5
6
7
8
9
10
function EmployeePage({ enabled }: { enabled: boolean }) {
// 错误:Hook 是否调用取决于条件
// if (enabled) useEffect(() => { ... }, []);
useEffect(() => {
if (!enabled) return; // 条件写在 Effect 内部
// ...
}, [enabled]);
return null;
}
提前 return 要放在所有 Hook 之后;如果某个分支需要一组完全不同的 Hook,把它拆成独立组件,用条件渲染选择组件。
state 还是 ref
| 情况 | 选择 |
|---|---|
| 改变后界面必须更新 | state |
| 保存 DOM 节点 | ref |
定时器 ID、AbortController、上一次的值等不显示在界面上的数据 | ref |
| 能从当前 state 或 props 算出来 | 渲染时直接计算,必要时 useMemo |
| 来自外部存储(浏览器 API、全局 store)且需要显示 | useSyncExternalStore |
1
2
3
4
5
6
7
8
9
function Search() {
const inputRef = useRef<HTMLInputElement>(null);
return (
<>
<input ref={inputRef} />
<button onClick={() => inputRef.current?.focus()}>聚焦搜索框</button>
</>
);
}
React 19 中 ref 是普通 prop,函数组件可以直接接收 ref 并转交给内部元素,不再需要 forwardRef。
不要在渲染中读写 ref.current
react.dev 的 useRef 文档要求:除初始化外,不要在渲染期间读写 ref.current。唯一允许的模式是惰性初始化:
1
2
3
4
const playerRef = useRef<VideoPlayer | null>(null);
if (playerRef.current === null) {
playerRef.current = new VideoPlayer();
}
渲染期间读 ref,读到的值可能不对应这次渲染的 props 和 state;渲染期间写 ref,被丢弃或重复执行的渲染也会留下修改。读写应放在事件处理函数和 Effect 里。
useId 用于关联无障碍属性
1
2
3
4
5
6
7
8
9
function NameField() {
const id = useId();
return (
<div>
<label htmlFor={`${id}-name`}>姓名</label>
<input id={`${id}-name`} />
</div>
);
}
同一个组件渲染多次,每个实例的 ID 不同,label 与 input 不会串到别的实例上(实验 3)。useId 不能用来生成列表 key:key 要在渲染列表时就确定,并且来自数据;useId 只能在列表项组件内部调用,值取决于挂载顺序或树中位置,和数据无关。它也不是数据库主键生成器。
什么逻辑值得写成自定义 Hook
- 与 React 状态和生命周期紧密相关的逻辑:订阅浏览器事件、加载异步资源、一套表单状态与提交流程、多个组件共享的交互状态机。
- 不需要提取的:纯计算。
queryEmployees、nextEmployeeId这样的函数保持为普通函数,在 React 之外也能复用和单测。用use开头命名一个不调用任何 Hook 的函数,会让 lint 规则对它施加不必要的限制。
每次调用自定义 Hook,内部的 Hook 都挂在调用它的组件的链表上,所以每个组件各有一份独立状态(实验 2 最后一项:两个组件调用同一个 useToggle,只切换甲,乙不受影响)。自定义 Hook 不是全局单例,需要跨组件共享同一份数据时,要把状态提升到共同父组件,或使用 Context、useSyncExternalStore。
一个 Hook 同时负责权限、路由、弹窗、请求和导出,说明职责边界没有划清。好的自定义 Hook 让调用方能看出它持有什么状态、产生什么副作用、何时更新。
在 TSX 中写类型
以下写法都在实验 4 中用 tsc --strict 检查过(TypeScript 7.0.2,对照 5.9.3;@types/react 19.3.3)。
Props 用接口描述,可选项给默认值:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface EmployeeRowProps {
employee: Employee;
onEdit: (employee: Employee) => void;
readOnly?: boolean;
}
function EmployeeRow({ employee, onEdit, readOnly = false }: EmployeeRowProps) {
return (
<tr>
<td>{employee.name}</td>
<td><button disabled={readOnly} onClick={() => onEdit(employee)}>编辑</button></td>
</tr>
);
}
初值是 null 或空数组时要写泛型。 useState(null) 推断出的类型是 null,之后 setSelected(employee) 报错;useState([]) 推断为 never[],任何元素都放不进去:
1
2
3
4
const [keyword, setKeyword] = useState(""); // string
const [selected, setSelected] = useState<Employee | null>(null);
const [employees, setEmployees] = useState<Employee[]>([]);
const [load, setLoad] = useState<LoadState>({ kind: "loading" });
DOM ref 写元素类型并传 null。 useRef<HTMLInputElement>(null) 的 current 类型包含 null,使用前要判空,直接 inputRef.current.focus() 报错 TS18047。
事件类型。 内联回调让 TypeScript 根据 JSX 位置推断;拆成命名函数时写 ChangeEvent<HTMLInputElement>、FormEvent<HTMLFormElement> 等。
包装原生元素时继承它的属性:
1
2
3
4
5
6
7
8
9
10
11
import type { ComponentProps } from "react";
type PrimaryButtonProps = ComponentProps<"button"> & { loading?: boolean };
function PrimaryButton({ loading = false, disabled, children, ...rest }: PrimaryButtonProps) {
return (
<button {...rest} disabled={disabled || loading}>
{loading ? "处理中…" : children}
</button>
);
}
这样 type、onClick 等标准属性都有类型检查,type="sumbit" 会被报出并提示 Did you mean '"submit"'?。是否透传全部属性,还要看这个组件对外承诺的 API 和无障碍要求。
children 用 ReactNode。 它包括元素、字符串、数字、null、数组等可渲染内容;把普通对象当子节点传入会报错。ReactElement 只表示元素对象,范围更窄。
Context 默认值为 null 时,包一层 Hook 检查:
1
2
3
4
5
6
7
8
interface Session { userId: string }
const SessionContext = createContext<Session | null>(null);
export function useSession(): Session {
const session = useContext(SessionContext);
if (session === null) throw new Error("useSession 必须在 SessionContext 内使用");
return session;
}
不要用 null as unknown as Session 绕过,那只是把缺少 Provider 的错误推迟到运行时。
泛型箭头函数在 .tsx 里写成 <T,>。 .tsx 中 <T>(value: T) => value 会被解析成 JSX 开标签,报 JSX element 'T' has no corresponding closing tag;加一个逗号 <T,>,或写成 function identity<T>(value: T)。
网络数据仍需运行时校验。 payload as Employee[] 能通过编译,但不会检查数据,id 是数字、name 缺失的数据照样进入组件树。类型守卫和运行时校验见 《TypeScript 类型擦除:类型在运行时不存在,外部数据怎样校验》。
失效条件
- 条件调用 Hook,导致 Hook 数量在两次渲染间变化。
- 触发条件:
if (flag) useState(...),或在部分 Hook 之前提前return。 - 后果:数量变多时抛
Rendered more hooks than during the previous render.,变少时抛Rendered fewer hooks than expected.。没有错误边界时整个根节点被卸载,实验 2 中容器内容变成空字符串。 - 如何观测:开发构建先输出
React has detected a change in the order of Hooks警告;生产构建是 Minified React error #310 / #300,可以到 react.dev/errors 查原文。
- 触发条件:
- 两个同类型 Hook 交换了调用顺序。
- 触发条件:不同分支里以不同顺序调用两个
useState,Hook 总数不变。 - 后果:状态静默错位,没有任何报错或警告。实验 2:
name=张三 age=28 → name=28 age=张三,console.error条数 0。这是违反规则后最难排查的情况。 - 如何观测:运行时无法发现,只能靠
eslint-plugin-react-hooks的rules-of-hooks在编码时拦截;出现「值莫名其妙对调」时检查 Hook 是否在分支里。
- 触发条件:不同分支里以不同顺序调用两个
- 不同类型 Hook 交换了位置。
- 触发条件:一个分支先
useState后useRef,另一个分支相反。 - 后果:
useState拿到的节点没有更新队列,抛出Should have a queue. You are likely calling Hooks conditionally, which is not allowed.(生产构建 #311)。 - 如何观测:同第 1 条的警告与错误。
- 触发条件:一个分支先
- 在组件外或渲染结束后调用 Hook。
- 触发条件:在事件处理函数、
setTimeout回调、普通工具函数中调用useState等。 - 后果:渲染结束后 dispatcher 被设为
ContextOnlyDispatcher,调用直接抛出Invalid hook call(生产构建 #321)。项目里装了两份 React(如 monorepo 中依赖版本不一致),也会出现同样的报错。 - 如何观测:错误信息中列出的三种原因;
npm ls react检查是否有多份 React。
- 触发条件:在事件处理函数、
- 用 ref 保存需要显示的数据。
- 触发条件:
ref.current++后期望界面变化。 - 后果:不会触发渲染,界面停留在旧值,直到别的原因引起渲染时才「突然跳变」。实验 3:点击 3 次修改 ref,渲染 0 次,显示
ref=0;再修改一次 state,渲染 1 次,显示ref=3 state=1。 - 如何观测:渲染计数;DevTools 中 ref 的值与界面不一致。
- 触发条件:
- 以为自定义 Hook 在组件之间共享状态。
- 触发条件:两个组件都调用
useCart(),期望一个组件添加商品后另一个组件也看到。 - 后果:每个组件各有一份 state,互不影响(实验 2:
甲:开乙:关)。 - 如何观测:DevTools 中两个组件下分别出现各自的 Hook 状态;需要共享时改用状态提升、Context 或外部 store。
- 触发条件:两个组件都调用
- 用类型断言掩盖类型问题。
- 触发条件:大量使用
as、非空断言!、// @ts-ignore,或response.json() as T。 - 后果:编译通过,错误数据或缺失的 Provider 在运行时才暴露,报错位置远离真正的原因。实验 4 中
payload as Employee[]没有任何编译错误。 - 如何观测:代码审查中检索
as、!.、@ts-ignore;在数据入口加运行时校验并记录失败。
- 触发条件:大量使用
实验验证
环境:Docker node:22(Node v22.23.5),react 19.3.1、react-dom 19.3.1、jsdom 31.0.1;类型检查用 typescript 7.0.2(对照 5.9.3)、@types/react 19.3.3。运行时实验在 jsdom 中用 createRoot 渲染,不使用 act。脚本和输出在 source/experiments/frontend/fe-b/react/:
| 实验 | 脚本 | 输出 |
|---|---|---|
| 1、2 Hook 链表与规则 | exp05_hooks.mjs | out/exp05_hooks.dev.out、out/exp05_hooks.prod.out |
| 3 ref 与 useId | exp09_ref_id.mjs | out/exp09_ref_id.dev.out |
| 4 TSX 类型检查 | tsx/types_ok.tsx、tsx/generic_arrow.tsx、tsx/run.sh | out/exp08_tsx.out |
实验 1:Hook 链表
输出见「底层机制」一节。alternate=null 说明这是只渲染过一次的 Fiber;return.tag=3 说明它的父节点是 HostRoot。读取 __reactFiber$ 属性只用于观察,它是 React 的私有实现,不要在业务代码中使用。
实验 2:违反调用顺序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
条件 Hook flag false → true:
React has detected a change in the order of Hooks called by Conditional. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks
onUncaughtError: Rendered more hooks than during the previous render.
容器内容: ""
条件 Hook flag true → false:
onUncaughtError: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.
容器内容: ""
同类型 Hook 调换顺序: name=张三 age=28 → name=28 age=张三;console.error 条数 0
useState/useRef 互换位置:
React has detected a change in the order of Hooks called by Mixed. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks
onUncaughtError: Should have a queue. You are likely calling Hooks conditionally, which is not allowed. (https://react.dev/link/invalid-hook-call)
组件外调用 useState 抛出: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
两个组件调用同一个自定义 Hook,只切换甲: 甲:开乙:关
flag true → false 这一项没有先出现顺序警告。开发构建的类型比较发生在每次调用 Hook 时,只比较已经调用到的位置。这一项少掉的是中间的 Hook,第二个位置上旧的是 useState、新的也是 useState,类型一致;缺少的节点要到函数结束、finishRenderingHooks 检查链表时才被发现。生产构建中同样位置的输出为 Minified React error #310、#300、#311、#321。
实验 3:ref 与 useId
1
2
3
4
点击 3 次 ref 按钮: 渲染 0 次,显示 "ref=0 state=0"
再点击 1 次 state 按钮: 渲染 1 次,显示 "ref=3 state=1"
useId 两次渲染记录: 姓名:_r_0_ 邮箱:_r_1_ 姓名:_r_0_ 邮箱:_r_1_
label[for] 与 input[id] 一致: true
两个 Field 实例的 ID 不同,第二次渲染与第一次相同。
实验 4:TSX 类型检查
types_ok.tsx 中故意写错的六行,tsc 都报了错,其余写法通过。下面是 7.0.2 的输出:
1
2
3
4
5
6
7
8
9
10
11
12
===== Version 7.0.2
== tsc -p tsconfig.json (types_ok.tsx)
types_ok.tsx(15,14): error TS2345: Argument of type 'number' is not assignable to parameter of type 'SetStateAction<string>'.
types_ok.tsx(16,15): error TS2345: Argument of type 'Employee' is not assignable to parameter of type 'SetStateAction<null>'.
...
types_ok.tsx(18,12): error TS2322: Type 'Employee' is not assignable to type 'never'.
types_ok.tsx(20,3): error TS18047: 'inputRef.current' is possibly 'null'.
types_ok.tsx(35,35): error TS2820: Type '"sumbit"' is not assignable to type '"button" | "reset" | "submit" | undefined'. Did you mean '"submit"'?
types_ok.tsx(45,30): error TS2353: Object literal may only specify known properties, and 'text' does not exist in type 'Iterable<ReactNode> | Promise<AwaitedReactNode> | ReactElement<unknown, string | JSXElementConstructor<any>> | ReactPortal'.
== tsc generic_arrow.tsx
generic_arrow.tsx(2,26): error TS17008: JSX element 'T' has no corresponding closing tag.
...
5.9.3 报出的错误码和位置完全相同,只是联合类型成员的显示顺序不同。第 15、16、18 行对应 setKeyword(42)、setSelected(employee)(初值为 null 未写泛型)、setList([employee])(初值为 [] 未写泛型);第 50 行的 payload as Employee[] 没有报错。
实际项目应用
Hook 的调用规则只能靠静态检查保证,项目里把官方插件的两条规则都打开。ESLint flat config 写法:
1
2
3
4
5
6
7
8
9
10
11
12
13
// eslint.config.js
import reactHooks from "eslint-plugin-react-hooks";
export default [
{
files: ["**/*.{js,jsx,ts,tsx}"],
plugins: { "react-hooks": reactHooks },
rules: {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
},
},
];
rules-of-hooks 设为 error,违反它的代码一定有隐患。exhaustive-deps 的警告不要用 eslint-disable 压掉,按提示补依赖,或把不需要触发重新执行的值移进 Effect、改成 ref 或 useEffectEvent。
CI 中运行 eslint --max-warnings 0,避免警告逐渐堆积。出现 Invalid hook call 时,先用 npm ls react react-dom 确认依赖树里只有一份 React,monorepo 中用包管理器的去重或 overrides 统一版本。
