简体   繁体   English

useEffect 和 useMemo 的区别

[英]Difference between useEffect and useMemo

I'm trying to wrap my head around what exactly the useMemo() React hook is.我正在努力useMemo() React 钩子究竟是什么。

Suppose I have this useMemo :假设我有这个useMemo

const Foo = () => {
  const message = useMemo(() => {
    return readMessageFromDisk()
  }, [])

  return <p>{message}</p>
}

Isn't that exactly the same as using a useState() and useEffect() hook?这与使用useState()useEffect()挂钩不完全一样吗?

const MyComponent = () => {
  const [message, setMessage] = useState('')
  
  useEffect(() => {
    setMessage(readMessageFromDisk())
  }, [])

  return <p>{message}</p>
}

In both cases the useMemo and useEffect will only call if a dependency changes.在这两种情况下, useMemouseEffect只会在依赖项发生变化时调用。

And if both snippes are the same: what is the benefit of useMemo ?如果两个片段相同: useMemo 的好处是什么

Is it purely a shorthand notation for the above useEffect snippet.它是否纯粹是上述useEffect片段的简写符号。 Or is there some other benefit of using useMemo ?还是使用useMemo有其他好处?

useEffect is used to run the block of code if the dependencies change. useEffect用于在依赖项发生变化时运行代码块。 In general you will use this to run specific code on the component mounting and/or every time you're monitoring a specific prop or state change.通常,您将使用它在组件安装和/或每次监视特定propstate更改时运行特定代码。

useMemo is used to calculate and return a value if the dependencies change.如果依赖关系发生变化, useMemo用于计算并返回一个值。 You will want to use this to memoize a complex calculation, eg filtering an array.你会想用它来记住一个复杂的计算,例如过滤一个数组。 This way you can choose to only calculate the filtered array every time the array changes (by putting it in the dependency array) instead of every render.这样您就可以选择在每次数组更改时(通过将其放入依赖数组)而不是每次渲染时只计算过滤后的数组。

useMemo does the same thing as your useEffect example above except it has some additional performance benefits in the way it runs under the hood. useMemo与上面的useEffect示例做同样的事情,除了它在引擎盖下运行的方式有一些额外的性能优势。

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

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