useMemo hook in ReactJS | Advantages and Cost

useMemo hook in ReactJS | Advantages and Cost

useMemo is built in hook in reactjs to memoize expensive operations in ReactJS.

There are many operations leads to re-render the component eg. state updates, props updates. Re-rendering can cause some of the functions to execute again. If synchronus functions takes more time it adds the pause to render the component. Sometimes, these functions returns same data for same input, but unnecessarily React re-calculate the functions.

const MyComponent = props => {

    const [physics, chemistry, math] = [80, 84, 98];
    const expensiveGetResult= (physics, chemistry, math) => {
            for(let i = 0; i < 1000000; i++);
            return physics + chemistry + math;
    }

    const result= expensiveGetResult(physics, chemistry, math);
    return(<>
       <span> Total = { result } </span>
   </>)

}

I have created hypothetical slow functions called expensiveGetResult. Now let's make some state variables so component re-renders.

const MyComponent = props => {

    const [counter, setCounter] = useState(0);
    const [physics, chemistry, math] = [80, 84, 98];

    const expensiveGetResult= (physics, chemistry, math) => {
        const t0 = performance.now();
        for(let i = 0; i < 1000000; i++);
        const t1 = performance.now();
        console.log(`Call to doSomething took ${t1 - t0} milliseconds.`);
        return physics + chemistry + math;
    }

    useEffect( () => {
        setInterval( () => {
            setCounter(prev => prev + 1);
        }, 1000);
    }, []);

    const result= expensiveGetResult(physics, chemistry, math);
    return(<>
       <span> Total = { result } </span>
   </>)

}

Now, as our state is changing we are re-calculating the expensiveGetResult function thought it's given same result and inputs result.

Let's see our result when we are running our application.

use-memo.PNG

As you can see many logs and functions execution time. All these milliseconds are doing duplicate work. Let's try to use useMemo and see if we can have better performance.

performance-3.PNG

As you can see in the screenshot our expensive functions isn't re-calculating multiple tines. (Note: I am monitoring app for same amount of time)

what does ReactJS save to memoize?

Look at the context of useMemo, React is memoizing in array with 0 stores result and 1 stores the dependancies.

performance-4.png