is it possible to use useMemo hook inside contitional statement?
Asked Answered
N

1

10

I was trying to use react hooks inside conditional statement unfortunatly react gives you error for almost all the hooks and its intented as per hooks philosophy.

and then I tried useMemo hook inside else statement and it worked no errors. I googled around for this discrepancy and i didn't find anything promising.

My question, Is useMemo an exception that you can use useMemo in conditional statement.

Negotiation answered 19/2, 2021 at 9:53 Comment(0)
C
19

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}/>;
}
Cuthbert answered 19/2, 2021 at 10:3 Comment(2)
yeah I am using the second alternative. that looks more natural. I am quite surprised that it didn't gave me error when I used useMemo hook inside else statement.Negotiation
If you have exactly one useMemo call in the if block and exactly one useMemo call in the else block, React will probably not notice that those are different ones, as it can only detect the number and type of hooks and the order in which they are called. So it might not throw an exception, but it will probably not work in the way that you intend.Cuthbert

© 2022 - 2024 — McMap. All rights reserved.