蓝色天空网mbsky.com · 知识 · 实践 · 创造React · 本地阅读预览
教程 / 前端开发 / React

React Hooks

核对 React 16.8 引入的 Hooks 体系,系统覆盖 useState、useEffect、useContext、useReducer、useCallback、useMemo、useRef、useImperativeHandle、useLayoutEffect、useDebugValue、自定义 Hook 与顶层调用规则,并以离线 Chromium 实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

Hooks 定位、useState 与 useEffect 核心机制

React Hooks 自 React 16.8 引入,是一套面向函数组件的增强机制,使开发者无需编写类组件即可直接使用局部状态、副作用生命周期与上下文等核心能力。最基础的 `useState(initialState)` 返回 `[state, setState]` 二元组,用于跟踪随交互变化的数据(如计数器 `count`)。

`useEffect(setup, deps)` 用于在渲染提交后执行数据获取、定时器订阅或手动更新 `document.title` 等副作用,相当于类组件 `componentDidMount`、`componentDidUpdate` 与 `componentWillUnmount` 的统一抽象:省略依赖数组时每次渲染后运行,传入空数组 `[]` 时仅在挂载与卸载时运行,传入 `[count]` 时仅在 `count` 变化时重新执行,并返回清理函数用于释放定时器或订阅。本站离线 Chromium 实测(`usestate_and_useeffect_title_and_cleanup`):点击计数器 2 次后页面标题与文案同步为 `You clicked 2 times`,随后触发无关状态更新时标题副作用计数保持 `3`(不重复运行);定时器组件卸载触发清理函数后,后续时间片内秒数不再增长。

核心内置 Hooks 全景对照与执行时机实测

围绕状态与数据流,除 `useState` 与 `useEffect` 外,常用内置 Hook 还包括:读取跨层级上下文避免逐层透传 props 的 `useContext(MyContext)`,以及以 `(state, action) => nextState` 纯函数管理复杂状态机并返回 `[state, dispatch]` 的 `useReducer(reducer, initialState)`。本站实测(`usecontext_and_usereducer_state_flow`):深层节点直接消费 `ThemeContext` 值 `ocean-dark`;`useReducer` 依次派发 `increment`、`add(4)`、`reset`、`add(3)` 后中间值为 `5`、终值为 `3` 且操作轨迹 `['+1', '+4', 'reset', '+3']` 精确可溯。

围绕性能优化、DOM 句柄与调试,React 提供:`useCallback(fn, deps)` 缓存回调函数引用;`useMemo(() => compute(a, b), [a, b])` 缓存派生计算结果;`useRef(initialValue)` 持有跨渲染持久化引用或 DOM 节点;`useImperativeHandle(ref, createHandle)` 定制对外暴露的实例方法;`useLayoutEffect` 在 DOM 变更完成后、浏览器绘制前同步执行(适合同步读取布局避免闪烁);以及在 React DevTools 中标注自定义 Hook 调试信息的 `useDebugValue(value)`。本站实测(`usememo_usecallback_useref_layout_order`):依赖不变时 `useCallback` 返回同一函数引用、`useMemo` 仅在依赖由 `5` 变为 `7` 时重算(总计算 `2` 次而非 `3` 次),`useRef` 忠实计数 `3` 次渲染,`useImperativeHandle` 读取 `#box` 宽度为 `120` px,且实测时序严格遵循 `['render', 'layoutEffect', 'effect']`。

Hooks 工程收益、调用规则与自定义 Hook 复用

采用 Hooks 的核心收益在于:以更精简的函数组件替代繁琐类模板、借由自定义 Hook(以 `use` 开头)跨组件复用状态逻辑并独立测试,以及借助依赖数组精细控制副作用与计算开销。使用时必须遵守两条硬性规则:其一,**仅在函数组件或自定义 Hook 的最顶层调用 Hook**,切勿放进条件分支、循环或嵌套函数中,因为 React 依靠每次渲染完全一致的调用顺序按槽位索引对应状态;其二,在项目中启用官方 `eslint-plugin-react-hooks` 插件自动检查依赖项与调用位置。本站实测(`custom_hook_reuse_and_top_level_order_rule`):自定义 `useCounter` 供两个组件独立调用并记录 `useDebugValue` 标签(`compA=15 / counter:15`、`compB=1 / counter:1`);而将第一个 `useState` 放入 `if (cond)` 后,当 `cond` 由 `true` 变为 `false` 时,第二个 Hook 槽位发生错位,错误读取到了原首槽位的值 `'A'`,直观印证了顶层顺序约束的底层原因。

在无头 Chromium 中离线验证核心 Hooks 行为、useLayoutEffect 时序、自定义 Hook 隔离与条件调用错位机理

python · 阅读源码
"""Offline Playwright Chromium verification for React Ch30 (hooks)."""
import json
from playwright.sync_api import sync_playwright


def launch_browser(p):
    for kwargs in (
        dict(headless=True),
        dict(headless=True, channel="chrome"),
        dict(headless=True, channel="msedge"),
    ):
        try:
            return p.chromium.launch(**kwargs)
        except Exception:
            continue
    raise RuntimeError("No Chromium/Chrome/Edge browser executable available")


def case_usestate_and_useeffect_title_and_cleanup(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"><title>Initial</title></head>
<body>
  <p id="cnt-text"></p>
  <button id="inc">Click me</button>
  <button id="noop-other">Other</button>
  <p id="timer-text"></p>
  <script>
    let count = 0, other = 0, titleEffectRuns = 0;
    let prevCountDep = undefined;
    function renderExample() {
      document.getElementById('cnt-text').textContent = `You clicked ${count} times`;
      if (prevCountDep !== count) {
        prevCountDep = count;
        titleEffectRuns += 1;
        document.title = `You clicked ${count} times`;
      }
    }
    document.getElementById('inc').addEventListener('click', () => { count += 1; renderExample(); });
    document.getElementById('noop-other').addEventListener('click', () => { other += 1; renderExample(); });
    renderExample();

    // Timer with useEffect(..., []) + cleanup
    let seconds = 0, cleanupCalled = false;
    const timerId = setInterval(() => {
      seconds += 1;
      document.getElementById('timer-text').textContent = `Timer: ${seconds} seconds`;
    }, 30);
    window.__unmountTimer = () => {
      clearInterval(timerId);
      cleanupCalled = true;
    };
    window.__getRes = () => ({
      title: document.title,
      cntText: document.getElementById('cnt-text').textContent,
      titleEffectRuns,
      cleanupCalled,
      seconds,
    });
  </script>
</body></html>"""
    page.set_content(html)
    page.click("#inc")
    page.click("#inc")
    page.click("#noop-other")
    page.wait_for_function("window.__getRes().seconds >= 2")
    page.evaluate("window.__unmountTimer()")
    sec_at_unmount = page.evaluate("window.__getRes().seconds")
    page.wait_for_timeout(90)
    res = page.evaluate("window.__getRes()")
    actual = {
        "title": res["title"],
        "cntText": res["cntText"],
        "titleEffectRuns": res["titleEffectRuns"],
        "cleanupCalled": res["cleanupCalled"],
        "ticksStoppedAfterUnmount": res["seconds"] == sec_at_unmount,
    }
    expected = {
        "title": "You clicked 2 times",
        "cntText": "You clicked 2 times",
        "titleEffectRuns": 3,
        "cleanupCalled": True,
        "ticksStoppedAfterUnmount": True,
    }
    return dict(name="usestate_and_useeffect_title_and_cleanup", expected=expected, actual=actual, passed=(actual == expected))


def case_usecontext_and_usereducer_state_flow(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <div id="badge"></div>
  <div id="sum"></div>
  <script>
    function createContext(defaultValue) { return { _current: defaultValue }; }
    function useContext(ctx) { return ctx._current; }
    const ThemeContext = createContext('light');
    ThemeContext._current = 'ocean-dark';
    const consumedTheme = useContext(ThemeContext);
    document.getElementById('badge').textContent = `theme=${consumedTheme}`;

    function reducer(state, action) {
      switch (action.type) {
        case 'increment': return { count: state.count + 1, history: [...state.history, '+1'] };
        case 'add': return { count: state.count + action.payload, history: [...state.history, '+' + action.payload] };
        case 'reset': return { count: 0, history: [...state.history, 'reset'] };
        default: return state;
      }
    }
    let state = { count: 0, history: [] };
    const dispatch = (action) => { state = reducer(state, action); };
    dispatch({ type: 'increment' });
    dispatch({ type: 'add', payload: 4 });
    const mid = state.count;
    dispatch({ type: 'reset' });
    dispatch({ type: 'add', payload: 3 });
    document.getElementById('sum').textContent = String(state.count);
    window.__res = {
      theme: document.getElementById('badge').textContent,
      midCount: mid,
      finalCount: state.count,
      history: state.history,
    };
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("window.__res")
    expected = {
        "theme": "theme=ocean-dark",
        "midCount": 5,
        "finalCount": 3,
        "history": ["+1", "+4", "reset", "+3"],
    }
    return dict(name="usecontext_and_usereducer_state_flow", expected=expected, actual=actual, passed=(actual == expected))


def case_usememo_usecallback_useref_layout_order(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <div id="box" style="width:120px;height:40px"></div>
  <script>
    const order = [];
    let computeRuns = 0;
    let memoValCache = null, memoValDeps = null;
    function useMemo(fn, deps) {
      if (memoValDeps && deps.every((d, i) => Object.is(d, memoValDeps[i]))) return memoValCache;
      memoValDeps = deps.slice();
      computeRuns += 1;
      memoValCache = fn();
      return memoValCache;
    }
    let cbCache = null, cbDeps = null;
    function useCallback(fn, deps) {
      if (cbDeps && deps.every((d, i) => Object.is(d, cbDeps[i]))) return cbCache;
      cbDeps = deps.slice();
      cbCache = fn;
      return cbCache;
    }
    const renderRef = { current: 0 };

    // Simulate 2 renders with same dep a=5, then 1 render with a=7
    const f1 = useCallback(() => 'ok', [5]);
    const v1 = useMemo(() => 5 * 10, [5]);
    renderRef.current += 1;
    const f2 = useCallback(() => 'ok', [5]);
    const v2 = useMemo(() => 5 * 10, [5]);
    renderRef.current += 1;
    const v3 = useMemo(() => 7 * 10, [7]);
    renderRef.current += 1;

    // useImperativeHandle restricted facade
    const boxEl = document.getElementById('box');
    const handle = { getWidth: () => boxEl.getBoundingClientRect().width };

    // useLayoutEffect runs synchronously after DOM commit, before rAF/useEffect
    order.push('render');
    // synchronous layout effect
    const measuredWidth = handle.getWidth();
    order.push('layoutEffect');
    window.__done = new Promise((resolve) => {
      requestAnimationFrame(() => {
        order.push('effect');
        resolve({
          sameCallbackRef: f1 === f2,
          memoValues: [v1, v2, v3],
          computeRuns,
          refRenders: renderRef.current,
          measuredWidth,
          executionOrder: order,
        });
      });
    });
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("window.__done")
    expected = {
        "sameCallbackRef": True,
        "memoValues": [50, 50, 70],
        "computeRuns": 2,
        "refRenders": 3,
        "measuredWidth": 120,
        "executionOrder": ["render", "layoutEffect", "effect"],
    }
    return dict(name="usememo_usecallback_useref_layout_order", expected=expected, actual=actual, passed=(actual == expected))


def case_custom_hook_reuse_and_top_level_order_rule(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <script>
    // Minimal React fiber-like Hook cursor showing custom hook isolation & why conditional hooks corrupt slots
    function createFiber() {
      return { hooks: [], cursor: 0, debugLabels: [] };
    }
    let activeFiber = null;
    function useState(init) {
      const f = activeFiber;
      const idx = f.cursor++;
      if (f.hooks.length <= idx) f.hooks.push(init);
      return [f.hooks[idx], (val) => { f.hooks[idx] = typeof val === 'function' ? val(f.hooks[idx]) : val; }];
    }
    function useDebugValue(label) {
      activeFiber.debugLabels.push(label);
    }
    function useCounter(initial, step) {
      const [val, setVal] = useState(initial);
      useDebugValue(`counter:${val}`);
      return { val, inc: () => setVal((c) => c + step) };
    }

    const fiberA = createFiber();
    const fiberB = createFiber();
    function renderCounter(fiber, initial, step) {
      activeFiber = fiber;
      fiber.cursor = 0;
      fiber.debugLabels = [];
      return useCounter(initial, step);
    }
    let a = renderCounter(fiberA, 10, 5);
    a.inc();
    a = renderCounter(fiberA, 10, 5);
    let b = renderCounter(fiberB, 0, 1);
    b.inc();
    b = renderCounter(fiberB, 0, 1);

    // Demonstrate Hook slot shift when calling useState inside an `if` branch
    const badFiber = createFiber();
    function brokenComponent(cond) {
      activeFiber = badFiber;
      badFiber.cursor = 0;
      let first = null;
      if (cond) {
        [first] = useState('A');
      }
      const [second] = useState('B');
      return { first, second };
    }
    const r1 = brokenComponent(true);  // slot0='A', slot1='B'
    const r2 = brokenComponent(false); // slot0 read as `second` -> wrongly gets 'A'!
    window.__res = {
      compA: a.val,
      compB: b.val,
      debugA: fiberA.debugLabels[0],
      debugB: fiberB.debugLabels[0],
      validFirstRender: r1,
      conditionalHookCorruptedSecond: r2.second,
    };
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("window.__res")
    expected = {
        "compA": 15,
        "compB": 1,
        "debugA": "counter:15",
        "debugB": "counter:1",
        "validFirstRender": {"first": "A", "second": "B"},
        "conditionalHookCorruptedSecond": "A",
    }
    return dict(name="custom_hook_reuse_and_top_level_order_rule", expected=expected, actual=actual, passed=(actual == expected))


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            cases = [
                case_usestate_and_useeffect_title_and_cleanup(page),
                case_usecontext_and_usereducer_state_flow(page),
                case_usememo_usecallback_useref_layout_order(page),
                case_custom_hook_reuse_and_top_level_order_rule(page),
            ]
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 useEffect 依赖过滤与卸载清理、useContext/useReducer 状态流、useMemo/useCallback 缓存及 render→layoutEffect→effect 时序,以及条件调用 Hook 导致的槽位错位。
在无头 Chromium 中离线验证核心 Hooks 行为、useLayoutEffect 时序、自定义 Hook 隔离与条件调用错位机理

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:3f6c8a405221bd5f758ffe1cac970e536d4989abf69d9e67399aec57b17c86c4

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载React Hooks实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:e1e0d848d601c9c6f677ea3878c7e36ccf97b16d5209ac7fdf51fdd7017f0136

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么 React 规定 Hooks 只能在顶层调用而不能写在 if 条件语句中?useLayoutEffect 与 useEffect 的执行时机有何区别?

展开参考解答

React 内部按顺序数组(链表槽位)存储每个组件的 Hook 状态,条件调用会改变后续渲染的调用序号导致状态错位读取;useLayoutEffect 在 DOM 变更提交后、浏览器绘制屏幕前同步执行,而 useEffect 在浏览器完成绘制后异步执行。

规范与官方依据