Skip to content

useRef 修改不触发重渲染

快速摘要

你更新了 ref.current 但组件没有重渲染 —— useRef 的修改不被 React 追踪,不触发更新。

为什么发生

  • 你用 useRef 存储应该是响应式状态的值,但 ref 变化不导致重渲染

  • 你修改了 ref.current 并期望 UI 更新,但 React 不观察 ref 变化

  • 你混淆了 useState 和 useRef 语义,用 ref 存储驱动渲染的数据

最小示例

✗ 错误代码
function Timer() {
  const seconds = useRef(0);
  useEffect(() => {
    const id = setInterval(() => {
      seconds.current++; // no re-render!
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return <div>{seconds.current}</div>; // always shows 0
}
✓ 修复代码
function Timer() {
  const [seconds, setSeconds] = useState(0);
  useEffect(() => {
    const id = setInterval(() => {
      setSeconds(s => s + 1); // triggers re-render
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return <div>{seconds}</div>; // updates every second
}

用 useState 替代 useRef 使值变为响应式 —— 每次更新触发重渲染,UI 反映新值。

如何诊断

  • 记录 ref.current 值确认它已变化,然后检查 UI 是否更新以验证脱节

  • 审查该值是否应触发重渲染 —— 如果是,应该用 useState 而非 useRef

  • 在渲染函数顶部添加 console.log 检查组件是否重渲染

如何修复

  • 将应该触发重渲染的值从 useRef 改为 useState

  • 修改 ref 后通过调用虚拟状态 setter 强制重渲染:const [, force] = useState(0); force(x => x + 1)

  • 保留 ref 用于可变存储,同时维护一个状态镜像,需要 UI 反映变化时更新它

如何预防

  • useRef 仅用于不需要触发重渲染的值(DOM 引用、计时器、可变容器)

  • 任何驱动渲染的值使用 useState —— 永远不要用 ref 作为响应式状态替代

相关资源

相关术语

相关课程

← 返回语言