验证编译器是否保留了现有的手动记忆。React 编译器仅在其推断为 匹配或超过现有的手动记忆 时才会编译组件和钩子。
¥Validates that existing manual memoization is preserved by the compiler. React Compiler will only compile components and hooks if its inference matches or exceeds the existing manual memoization.
规则详情
¥Rule Details
React Compiler 会保留你现有的 useMemo
、useCallback
和 React.memo
调用。如果你手动记住了某些内容,编译器会假定你有充分的理由这样做,并且不会将其移除。不完整的依赖会阻止编译器理解代码的数据流并进行进一步的优化。
¥React Compiler preserves your existing useMemo
, useCallback
, and React.memo
calls. If you’ve manually memoized something, the compiler assumes you had a good reason and won’t remove it. However, incomplete dependencies prevent the compiler from understanding your code’s data flow and applying further optimizations.
无效
¥Invalid
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
// ❌ Missing dependencies in useMemo
function Component({ data, filter }) {
const filtered = useMemo(
() => data.filter(filter),
[data] // Missing 'filter' dependency
);
return <List items={filtered} />;
}
// ❌ Missing dependencies in useCallback
function Component({ onUpdate, value }) {
const handleClick = useCallback(() => {
onUpdate(value);
}, [onUpdate]); // Missing 'value'
return <button onClick={handleClick}>Update</button>;
}
有效
¥Valid
此规则的正确代码示例:
¥Examples of correct code for this rule:
// ✅ Complete dependencies
function Component({ data, filter }) {
const filtered = useMemo(
() => data.filter(filter),
[data, filter] // All dependencies included
);
return <List items={filtered} />;
}
// ✅ Or let the compiler handle it
function Component({ data, filter }) {
// No manual memoization needed
const filtered = data.filter(filter);
return <List items={filtered} />;
}
故障排除
¥Troubleshooting
我应该删除手动记忆功能吗?
¥Should I remove my manual memoization?
你可能想知道 React Compiler 是否让手动记忆变得没有必要:
¥You might wonder if React Compiler makes manual memoization unnecessary:
// Do I still need this?
function Component({items, sortBy}) {
const sorted = useMemo(() => {
return [...items].sort((a, b) => {
return a[sortBy] - b[sortBy];
});
}, [items, sortBy]);
return <List items={sorted} />;
}
如果使用 React Compiler,你可以安全地将其移除:
¥You can safely remove it if using React Compiler:
// ✅ Better: Let the compiler optimize
function Component({items, sortBy}) {
const sorted = [...items].sort((a, b) => {
return a[sortBy] - b[sortBy];
});
return <List items={sorted} />;
}