Search code examples
reactjsreact-hooksreact-usememo

is it possible to use useMemo hook inside contitional statement?


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.


Solution

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