Memoization
Optimizing re-渲染使用 React.memo, useMemo, and useCallback.
你将学到
- 什么 memoization 是 and 当它 helps 性能
- Using React.memo 到 prevent 组件 re-渲染
- Using useMemo 到缓存 expensive calculations
- Using useCallback 到 stabilize 函数引用
概念讲解
What Is Memoization?
Memoization 是一种optimization technique that caches the result of an expensive operation and returns the cached value when the inputs have not changed。 In React, memoization prevents unnecessary re-renders and recalculations. However, memoization itself has a cost — comparing inputs and storing cached values — so it should be used judiciously, not on everything. Measure first, then optimize.
React.memo
React.memo is a higher-order component that wraps a component and prevents re-renders if its props have not changed. It does a shallow comparison of props by default. If the parent re-renders but the memoized child's props are the same, the child skips rendering. This is useful for expensive components in lists or components that receive stable props. You can provide a custom comparison function as the second argument for deeper comparisons.
useMemo
useMemo caches the result of a calculation between renders. It takes a factory function and a dependency array: useMemo(() => expensiveCalc(, b), [, b]). The calculation runs only when ` or b` changes; otherwise, the cached value is returned. Use it for genuinely expensive computations (sorting large arrays, complex transformations) or when you need to maintain referential equality of an object/array that is passed as a prop to a memoized child.
useCallback
useCallback caches a function definition between renders. It is equivalent to useMemo(() => fn, deps) but specialized for functions. Its primary use case is passing stable callbacks to memoized child components or as dependencies to other hooks. If a parent creates a new function on every render and passes it to a React.memo child, the child re-renders every time because the function reference changes. useCallback prevents this by returning the same function reference when dependencies are unchanged.
When Not to Memoize
Memoization is not free — React must store the previous value and compare dependencies on every render. For simple values or cheap calculations, the cost of memoization exceeds the savings. Only memoize when you have measured a performance problem or when maintaining referential equality is required for correctness (e.g., as a dependency of useEffect or a prop of a memoized child).
示例代码
import { useState, useMemo, useCallback, memo } from "react";
// memo prevents re-render if props are unchanged.
const ExpensiveItem = memo(function Item({ data, onSelect }) {
console.log("Item rendered");
return <li onClick={() => onSelect(data.id)}>{data.name}</li>;
});
function ItemList({ items }) {
const [query, setQuery] = useState("");
const [selected, setSelected] = useState(null);
// useMemo caches the filtered list — only recomputes when items or query change.
const filtered = useMemo(
() => items.filter(i => i.name.toLowerCase().includes(query.toLowerCase())),
[items, query]
);
// useCallback stabilizes the handler reference for memoized children.
const handleSelect = useCallback((id) => {
setSelected(id);
}, []);
return (
<div>
<input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search" />
<ul>
{filtered.map(item => (
<ExpensiveItem key={item.id} data={item} onSelect={handleSelect} />
))}
</ul>
<p>Selected: {selected}</p>
</div>
);
}
memo prevents 项 re-渲染当 Props 是 stable. useMemo caches 筛选列表. useCallback keeps handleSelect stable 所以 memoized 项做 不 re-渲染 unnecessarily.
动手试一试
- Code Diff
Compare 性能之前 and 之后添加 memoization.
- JSON Formatter
Inspect 大数据设置那个可能 benefit 从 useMemo 缓存.
常见错误
错误写法
Wrapping 一切 in useMemo and useCallback 通过默认
正确做法
Memoization 有它的 own cost (comparison + storage). Use 它仅 for genuinely expensive calculations or 到 maintain referential equality for memoized children. Measure 性能之前 and 之后到 确认它 helps.
错误写法
Using useCallback 不使用 React.memo on child
正确做法
useCallback alone 做不 prevent re-渲染. 它仅 stabilizes 函数引用. child 必须也 是 wrapped in React.memo for stable 引用到 prevent re-渲染. 不使用 memo, child re-渲染 regardless.
练习 Memoization
9 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。