Using React’s useMemo Hook

21 / Jan / 2024 by Najmuddin Kaishar 0 comments

Introduction

React has many built-in useful hooks that you can use in your application. With the release of React 16.8 introduces a new hook that is useMemo. This hook improves the performance of your application.

What Is useMemo()

useMemo() hook in React significantly improves the performance of your components. This hook is designed to optimize expensive calculations. The useMemo hook memoizes values in our React application. It enables the caching of a function’s result, triggering a recalculation only when the specified dependencies have changed.

Syntax: The ‘useMemo’ hook takes two arguments: eg- const memoizeValue = useMemo(() => {/* function */}, [/* Dependencies */]);

1. calculateValue(1st argument as a function):- It’s a function that performs complex and expensive calculations.

2. dependencies(2nd argument as an array):- The array of dependencies serves as the second argument for useMemo. These dependencies dictate whether the memoized value requires recalculation. If any of these dependencies change, the function invokes a new one, leading to the computation and caching of a fresh value.

In the above code, we are checking number is prime or not. There are two input fields above the code first input field checks whether the number is prime or not, and the second one stores the name.

The above function is called, and a number is passed in this function to check whether the number is prime or not.

/blog/wp-ttn-blog/uploads/2024/01/screen-capture-3.webm

In the above video, you can see logs checking the prime number and your Name, The Problem is that If you type the name field, the name state will update and always re-render the component and execute the checkThePrimeNumber function every time. You can see in the log.

As you know checkNumberIsPrimeOrNot is an expensive function and it’s executing every time. We can fix this with the help of built-in use that is useMemo(). First Import the hook.

In the above code, we use useMemo to memoize the value. Whenever the value of dependency again, it memoizes the value.

/blog/wp-ttn-blog/uploads/2024/01/screen-capture-4.webm

In the above Video, whenever updating the state of the name, the expensive checkThePrimeNumber function is not executing. You can see in the log.

Conclusion

To avoid the unnecessary re-renders of the component and improve the performance. The useMemo() is the most powerful optimization technique. It helps in caching the result to improve the performance.

Thanks for reading! Check out our other blog posts for more insights.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

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