preserve-manual-memoization

验证现有的手动记忆化是否被编译器保留。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 编译器会保留你现有的 useMemouseCallbackReact.memo 调用。如果你手动进行了 memoization,编译器会认为你有充分的理由,因此不会移除它。然而,不完整的依赖会阻止编译器理解你的代码的数据流,并应用进一步的优化。

🌐 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} />;
}