Skip to content

useMemo

一句话解释

useMemo 是 Hook 那个 caches (memoizes) computed 值, recomputing 它仅 当它的 dependencies 更改.

用大白话说

useMemo caches the result of a calculation. You pass a factory function and a dependency array: const value = useMemo(() => compute(a, b), [a, b]). React calls the factory on the first render and whenever a or b change; otherwise it returns the cached value.

Use useMemo for expensive calculations — sorting large arrays, complex transformations, deriving data from multiple sources. It prevents the calculation from running on every render when the inputs haven't changed.

useMemo is also used to preserve referential equality of objects/arrays passed as props to memoized child components. If you create a new array every render, React.memo on the child won't help — wrapping the array in useMemo keeps the same reference.

示例

jsx
const sortedItems = useMemo(() => {
  return items.sort((a, b) => a.name.localeCompare(b.name));
}, [items]);

// Sort only runs when items changes, not on every render.

排序是 expensive. useMemo caches 排序数组 and 仅 re-排序当 项数组引用更改.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表