反应:useState 还是 useRef? [英] React: useState or useRef?

查看:23
本文介绍了反应:useState 还是 useRef?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在useState() 和 useRef() 的内容.html" rel="noreferrer">Hooks FAQ" 并且我对一些似乎同时具有 useRef 和 useState 解决方案的用例感到困惑,我不确定哪种方式是正确的方式.

I am reading about React useState() and useRef() at "Hooks FAQ" and I got confused about some of the use cases that seems to have solution with useRef and useState at the same time, and I'm not sure which way it the right way.

来自Hooks FAQ"关于 useRef():

From the "Hooks FAQ" about useRef():

useRef() 钩子不仅仅用于 DOM 引用.ref"对象是一个通用容器,其当前属性是可变的并且可以保存任何值,类似于类上的实例属性."

"The useRef() Hook isn’t just for DOM refs. The "ref" object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class."

使用 useRef():

function Timer() {
  const intervalRef = useRef();

  useEffect(() => {
    const id = setInterval(() => {
      // ...
    });
    intervalRef.current = id;
    return () => {
      clearInterval(intervalRef.current);
    };
  });

  // ...
}

使用 useState():

function Timer() {
  const [intervalId, setIntervalId] = useState(null);

  useEffect(() => {
    const id = setInterval(() => {
      // ...
    });
    setIntervalId(id);
    return () => {
      clearInterval(intervalId);
    };
  });

  // ...
}

两个例子都会有相同的结果,但哪个更好 - 为什么?

Both examples will have the same result, but which one it better - and why?

推荐答案

两者的主要区别在于:

useState 导致重新渲染,useRef 不会.

useState causes re-render, useRef does not.

它们之间的共同点是,useStateuseRef 都可以在重新渲染后记住它们的数据.因此,如果您的变量决定了视图层渲染,请使用 useState.否则使用 useRef

The common between them is, both useState and useRef can remember their data after re-renders. So if your variable is something that decides a view layer render, go with useState. Else use useRef

我建议阅读这篇文章.

这篇关于反应:useState 还是 useRef?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆