简体   繁体   English

为什么使用 useRef (initialValue) 而不是 useMemo()?

[英]why using useRef (initialValue) instead of useMemo()?

As far as I understand, another purpose of useRef(initialValue) is to keep a variable whose reference address does not change whenever a re-render of that component in the function component.据我所知, useRef(initialValue) 的另一个目的是保持一个变量,只要在函数组件中重新渲染该组件,其引用地址就不会改变。

However, the same can be done with useMemo().但是,同样可以使用 useMemo() 来完成。 What's the difference between the two?两者有什么区别? which one is more performance.哪个性能更好。

import React, { useState, useMemo, useEffect, useRef } from 'react';

function App() {
  const [count, setCount] = useState(0);
  
  const myObj = useMemo(() => ({current: 0}), [])
  const myRef = useRef(0)

  useEffect(() => {
    myObj.current = myObj.current + 1;
    myRef.current = myRef.current + 1;
  })

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Increase Count Number </button>
      <span>{myObj.current}</span>
      <span>{myRef.current}</span>
    </div>
  );
}

export default App;

useMemo is intended to memoize the functions that are being called inside its argument function. useMemo旨在useMemo在其参数函数中调用的函数。

The way you're using it, the return value of useMemo is equivalent to the one of useRef .您使用它的方式, useMemo的返回值相当于useRef
However it won't make sense to the next person that'll read it, as this is not the case that useMemo is meant to be used in:然而,它对下一个阅读它的人来说没有意义,因为useMemo并非用于以下情况:

  1. The function has absolutely no reason to be memoized.函数绝对没有理由被记住。
  2. The dependency array is empty, hence the function is only being called once.依赖数组为空,因此该函数仅被调用一次。

Technically both can be interchanged as far as the dependency array is empty for useMemo .从技术上讲,只要useMemo的依赖项数组为空,两者就可以互换。 But if you want to recalculate the value based on a certain prop or state variable change you can use useMemo by putting them in the dependency array但是如果你想根据某个 prop 或 state 变量的变化重新计算值,你可以通过将它们放在依赖数组中来使用 useMemo

Technically same expressions技术上相同的表达

const ref = useRef(computeExpensiveValue(a, b));

const memoizedValue = useMemo(() => computeExpensiveValue(a, b));


// in above - ref.current and memoizedValue will be same

But if we want to recalculate the value if a or b changes then we should useMemo like below但是如果我们想在ab改变时重新计算值,那么我们应该像下面这样使用useMemo

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM