A Complete Guide to use useMemo Hook in React

As we all know that from time to time react components have to perform expensive calculations like filtering the employees names from big list of employees. In such cases where you can try to improve the performance of the components using memoization.

In this blog post we will be describing about how and when to useMemo() hook in react.

 About useMemo() hook

The useMemo() hook in react is generally a built in react hook which takes 2 arguments . The first argument is a function which computes the result and the second one is the dependency array.

Syntax:
const memoizedResult = useMemo(compute,result)
When the initial rendering happens the useMemo(compute,result) invokes the compute function and memoizes the result of the calculation and returns it to the component.
If during the next renderings the dependencies don’t change then the useMemo() doesn’t invoke the compute but it returns the value which is already being memoized.
But if the dependencies changes while rendering next time then the useMemo() invokes the compute function and then memoizes the new value and returns it.
An Example to explain useMemo() in detail
Here is a small implementation of useMemo() hook in react.
useMemo in React
In the above example we have used useMemo hook to reduce the slowness which is caused inside the isEven function by the while loop.
Using Memoization with Care
Whenever you want to implement useMemo() hook in react always try to profile the component with or without the hook. Only after coming to the conclusion whether memoization will be beneficial for the component or not you should use it in your code.
When you use memoization unappropriately you will harm the performance of the component.
Conclusion
The useMemo() hook in react is generally a built in react hook which takes 2 arguments . The first argument is a function which computes the result and the second one is the dependency array.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

0FansLike
3,498FollowersFollow
19,400SubscribersSubscribe
- Advertisement -spot_img

Latest Articles