验证 useMemo
钩子是否带有返回值。有关更多信息,请参阅 useMemo
文档。
¥Validates that the useMemo
hook is used with a return value. See useMemo
docs for more information.
规则详情
¥Rule Details
useMemo
用于计算和缓存开销较大的值,而不是用于副作用。如果没有返回值,useMemo
会返回 undefined
,这违背了它的初衷,并且可能表明你使用了错误的 hook。
¥useMemo
is for computing and caching expensive values, not for side effects. Without a return value, useMemo
returns undefined
, which defeats its purpose and likely indicates you’re using the wrong hook.
无效
¥Invalid
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
// ❌ No return value
function Component({ data }) {
const processed = useMemo(() => {
data.forEach(item => console.log(item));
// Missing return!
}, [data]);
return <div>{processed}</div>; // Always undefined
}
有效
¥Valid
此规则的正确代码示例:
¥Examples of correct code for this rule:
// ✅ Returns computed value
function Component({ data }) {
const processed = useMemo(() => {
return data.map(item => item * 2);
}, [data]);
return <div>{processed}</div>;
}
故障排除
¥Troubleshooting
我需要在依赖更改时运行副作用
¥I need to run side effects when dependencies change
你可能尝试使用 useMemo
来实现副作用:
¥You might try to use useMemo
for side effects:
// ❌ Wrong: Side effects in useMemo
function Component({user}) {
// No return value, just side effect
useMemo(() => {
analytics.track('UserViewed', {userId: user.id});
}, [user.id]);
// Not assigned to a variable
useMemo(() => {
return analytics.track('UserViewed', {userId: user.id});
}, [user.id]);
}
如果副作用需要响应用户交互而发生,最好将副作用与事件放在一起:
¥If the side effect needs to happen in response to user interaction, it’s best to colocate the side effect with the event:
// ✅ Good: Side effects in event handlers
function Component({user}) {
const handleClick = () => {
analytics.track('ButtonClicked', {userId: user.id});
// Other click logic...
};
return <button onClick={handleClick}>Click me</button>;
}
如果副作用将 React 状态与某些外部状态同步(反之亦然),请使用 useEffect
:
¥If the side effect sychronizes React state with some external state (or vice versa), use useEffect
:
// ✅ Good: Synchronization in useEffect
function Component({theme}) {
useEffect(() => {
localStorage.setItem('preferredTheme', theme);
document.body.className = theme;
}, [theme]);
return <div>Current theme: {theme}</div>;
}