【阅读React文档】React Hook API-- useMemo

416 阅读2分钟

前言

公司项目中看到用到了useMemo,react小菜鸟立马去查react文档(原文)理解一遍,以下为文档原文(感觉中文翻译怪怪得,还是结合一下英文版更好理解):

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

Returns a memoized value.

Pass a “create” function and an array of dependencies. useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.

Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.

If no array is provided, a new value will be computed on every render.

You may rely on useMemo as a performance optimization, not as a semantic guarantee.  In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.

理解

  • 返回一个memoized值。

可以理解为返回了一个缓存的值,相当于vue的计算属性,也是返回一个缓存值,只有依赖更新才会把缓存值更新。

  • 参数为:创建值的函数和依赖项数组。useMemo只会在某个依赖项发生改变时,才会重新计算缓存值。这个优化有助于避免在每次渲染都进行高开销计算。

  • 传入的函数会在渲染期间执行,注意不要在函数内部执行与渲染无关的操作。

  • 如果没有提供依赖项,则每次渲染都会重新计算值。

  • 可以将useMemo作为性能优化的手段,但是不要把它当作语义上的保证。将来,React 可能会选择“遗忘”以前的一些 memoized 值,并在下次渲染时重新计算它们····

是性能优化的手段,但不是代表语义上的缓存,将来react作出一些优化,可能不能保证一些值是缓存的。

总结

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

在a或b值发生改变的时候,执行computeExpensiveValue()函数;

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

每次触发渲染都会执行computeExpensiveValue()函数;