Optimize Your React App With useMemo Hook

Hello Developers in this blog i will show you how you can use useMemo hook to reduce load and optimize your react app

Let’s get started 🙂

First, create a new app using the following command

npx create-react-app

Then we will create a function that will get called on every render

const [count, setCount] = useState(0);
const expensiveCalculation = (num) => {
    for (let i = 0; i < 1000000000; i++) {
        num += 1;
    }
    return num;
};
const calculation = expensiveCalculation(count)

Now we are going to call calculation function in render method so it will get called on every state change

<div>
      <h2>Expensive Calculation</h2>
      {calculation}
</div>
<button onClick={()=> setCount((c)=> c + 1 )}>+</button>

Now When we will click on the increment button it will increment a count by 1 and will update state and then react will rerender the whole page because it has detected state changes in the component

And our calculation function will run unnecessarily

And it will take time to rerender the page and display to you the updated count value

But it’s not an issue, the issue is when we update a state other than the count our calculation function will get called unnecessarily

For example:

As you can see in the above video i am just adding todo by using setTodo but however, it is taking a lot of time to rerender the whole component and display the updated value of the todo list

Now we are going to fix it by using useMemo react hook

const calculation = useMemo(() => expensiveCalculation(count), [count])

useMemo hook will recompute value whenever one of the dependencies will change

In our case expensive function will be called whenever react detects changes in deps not on every setState

Demo:

Submit a Comment

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

Subscribe

Select Categories