I was trying to use React hooks inside conditional statements. Unfortunately, React gives you an error for almost all the hooks, and it is intended as per hooks philosophy.
Next, I tried useMemo
hook inside else
statement, and it worked with no errors.
I Googled around for this discrepancy and I did not find anything promising.
Is useMemo
an exception that you can use useMemo
in a conditional statement?
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}/>;
}