No, you cannot run useMemo
or any other React hooks in conditional statements. The same React hooks have to be called in the same order each time the component is rendered. In my opinion the way that hooks work is really counter-intuitive and is one, if not the main thing that makes React so hard to learn.
There are two possible workarounds, either move the condition inside the hook callback, or move the code into a separate component.
Take this example code:
function MyComponent() {
if (condition) {
const myVar = useMemo(() => { return value; }, [value]);
return <OtherComponent var={myVar}/>;
} else {
return <SomethingElse/>;
}
}
One alternative would be:
function MyComponent() {
const myVar = useMemo(() => {
if (condition) {
return value;
}
}, [condition, value]);
if (condition) {
return <OtherComponent var={myVar}/>;
} else {
return <SomethingElse/>;
}
}
Another alternative would be:
function MyComponent() {
if (condition) {
return <MyComponent2/>;
} else {
return <SomethingElse/>;
}
}
function MyComponent2() {
const myVar = useMemo(() => { return value; }, [value]);
return <OtherComponent var={myVar}/>;
}