How to use React useMemo hook to improve performance

React useMemo hook

One of the ways that you can improve the performance of React apps is by using the useMemo hook. This hook prevents expensive calculations from running on every render. The React useMemo takes two arguments: a function and a dependency array.

useMemo( function, dependancy_array)

Now, let us see how useMemo work by an example. The following short video clip shows how to experiment with a program that uses useMemo hook.

I use a calculation function with a for loop to simulate an expensive calculation in this app. I include the console.log() statement so that you can see in the background that the “calculate” function runs every time you click on the “Get Total” button if you do not use useMemo hook.

If you use useMemo, this function runs only one time as long as the dependency( length/limit ) is not changed. Otherwise, It will use the memoized value.

function calculate( length ){
  let sum = 0;
    for( let i = 0; i < length ; i++ ){
   
      sum = sum + i;
      console.log( i );
     
    }
 
  return sum; 
}

I put the about function in two components. The Mymemo component uses the useMemo hook. There is only one dependency( length / limit ) in the dependency array of the hook.

export function Mymemo({length }) { 
  const meorizeValue = useMemo(() => calculate( length ), [length]);
  return <>{ meorizeValue }</>;
}

export function Total({length }) { 
  const total = calculate( length);
  return <>{ total }</>;
}

How to run the program

  • Download the program in this repo (or git clone https://github.com/dineshigdd/USEMEMO.git in the terminal )
  • cd the root folder ( cd usememo )
  • npm install
  • npm run dev

Resources

Official documentation

The program to download

Vite.js to set up React

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top