useRef 反应挂钩的确切行为是什么?是否在每次重新渲染时重新创建对象?

What is the exact behaviour of useRef react hook? Does the object get recreated on each rerender?

我正在创建一个应用程序,我需要在初始渲染时创建一个对象并在整个组件生命周期内保留它。

我的代码现在看起来有点像:

function Component() {
  const obj = useRef(new Smth());
  return (
    <div>
      <button onClick={obj.current.p}>p</button>
      <button onClick={obj.current.c}>c</button>
    </div>
  );
};

React 文档说:

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

来自:https://reactjs.org/docs/hooks-reference.html#useref

看来我用的很到位。然而,Hooks FAQ 说:

You might also occasionally want to avoid re-creating the useRef() initial value. For example, maybe you want to ensure some imperative class instance only gets created once:

function Image(props) {
  // ⚠️ IntersectionObserver is created on every render
  const ref = useRef(new IntersectionObserver(onIntersect));
  // ...
}

useRef does not accept a special function overload like useState. Instead, you can write your own function that creates and sets it lazily:


function Image(props) {
  const ref = useRef(null);

  // ✅ IntersectionObserver is created lazily once
  function getObserver() {
    if (ref.current === null) {
      ref.current = new IntersectionObserver(onIntersect);
    }
    return ref.current;
  }

  // When you need it, call getObserver()
  // ...
}

来自:https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables

那么初始值是否重新创建?

So does the initial value get recreated or not?

是的,可以重新创建初始值,但随后会丢弃。因此,您可以在 useRef 中保留一些值,并且它不会在重新渲染之间丢失,您也可以根据需要修改它。

它是 useState,如果你将一个值传递给它的构造函数,它会被重新计算,但随后会被丢弃。您可以将函数传递给 useState ,它只会执行一次。显然根据文档,useRef 没有这样的选项。但是你可以根据文档来模拟它:

  // ✅ IntersectionObserver is created lazily once
  function getObserver() {
    if (ref.current === null) {
      ref.current = new IntersectionObserver(onIntersect);
    }
    return ref.current;
  }