Skip to content

useRef Hook

可变引用那个 persist 跨越渲染, accessing DOM 元素, and 存储值.

你将学到

  • 什么 useRef 是 and 如何它 differs 从 useState
  • Accessing DOM 元素 directly 使用 refs
  • 存储可变值 那个做 不触发 re-渲染
  • 当到 use ref 对比状态对比变量

概念讲解

What Is useRef?

useRef returns a mutable ref object whose .current property persists across re-renders. Unlike state, changing a ref does not trigger a re-render. This makes refs useful for storing values that React does not need to track for rendering purposes. The ref object stays the same (same identity) across every render, so you can safely mutate .current without worrying about stale closures.

Accessing DOM Elements

The most common use of refs is to access a DOM element directly. You pass the ref to a DOM element's ref prop, and React sets ref.current to the actual DOM node after mount. This lets you call imperative methods like focus(), scrollIntoView(), getBoundingClientRect(), or measure an element. This is the escape hatch for when you need to interact with the DOM in ways that declarative JSX cannot express.

Storing Mutable Values

Refs are also useful for storing any mutable value that should not trigger a re-render when it changes. Common examples include timer IDs (setInterval returns), previous values for comparison, and caches. Because mutating .current does not cause a re-render, the UI will not update to reflect the change — this is intentional. If the value should affect the UI, use useState instead.

Refs vs State vs Variables

A regular variable declared in the component body is re-created on every render, so it cannot persist values. State persists and triggers re-renders. Refs persist but do not trigger re-renders. Use a variable for values used only within a single render. Use state for values that should update the UI when they change. Use a ref for values that need to persist but should not update the UI directly.

forwardRef and useImperativeHandle

Sometimes a parent needs a ref to a child component's internal DOM element. Since React 19, you can pass refs as regular props, but in earlier versions you need forwardRef. The useImperativeHandle hook lets you customize what the parent sees when it accesses the ref — instead of the DOM node, you can expose specific methods. This is useful for creating reusable input components that expose focus() or 清晰() methods to parents.

示例代码

              import { useRef, useState, useEffect } from "react";

function Stopwatch() {
  const [seconds, setSeconds] = useState(0);
  const intervalRef = useRef(null);   // Store timer ID.
  const inputRef = useRef(null);       // Access DOM input.

  const start = () => {
    if (intervalRef.current) return; // Prevent duplicate intervals.
    intervalRef.current = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);
  };

  const stop = () => {
    clearInterval(intervalRef.current);
    intervalRef.current = null;
  };

  // Focus the input on mount using the DOM ref.
  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  return (
    <div>
      <input ref={inputRef} placeholder="Label for your timer" />
      <p>Elapsed: {seconds}s</p>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
    </div>
  );
}
            

intervalRef 存储 timer ID 不使用 triggering re-渲染. inputRef accesses DOM 输入到 call focus() imperatively on mount.

动手试一试

  • Code Diff

    Compare ref usage 模式当 refactoring 组件 logic.

  • JSON Formatter

    Inspect 数据结构你 可能存储 in refs.

常见错误

错误写法

Using ref for 状态那个应该触发 re-渲染

正确做法

更改 ref.current 做不 cause re-渲染. 如果 UI 应该更新当 值更改, use useState 相反. Refs 是 for 值那个 persist 但做 不 affect 渲染.

错误写法

读取 or 编写 ref.current 期间渲染

正确做法

React forbids 读取 or 编写 refs 期间渲染. 读取 and 编写 refs in 事件处理函数, 副作用, or 回调 — 不 in 组件请求体期间渲染.

练习 useRef Hook

6 个练习

练习 useRef Hook

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误