Optimizing React functional components(useMemo)

In this article, we will discuss the different ways to optimize the react functional components. These hooks that we will discuss will be very helpful in large applications to optimize the performance as well as improve the user experience. There are various hooks that used for optimization like useMemo, useCallback, useReducer etc. I will go to these hooks in detailed view in three articles. So, I will start with useMemo hook in this particular article.

useMemo

useMemo allows us to memoize the functions which are very expensive or having very high computation during each re-render and we don't want to run such functions on every render.

useMemo takes one function and the array of arguments. useMemo runs this function only when there is a change in these arguments. If we pass the empty array then it will run once and if we pass not an empty array then it will run every time the re-render happens. In useMemo the result is remembered, if we pass the same argument then it will return the memoized result without actually running the whole process. So now let’s dive into the example.

Output is:

In the above code, we have an increment button, on clicking of it will increase the count by one. The functional component also renders the high computation function which returns the sum. In that function, there is a console log which logs the sum every time the function runs.

In the output we can clearly see every time we click the button we get the sum value at the console, means the whole functional component gets rendered and the maxComputation re-runs and returns the value. Now let's use useMemo to optimize it.

Output

In the above code, we introduced the useMemo hook, replaced the maxComputation function with beforeMaxComputation and in useMemo we passed the maxComputation function with the second parameter which is an empty array.

In the console, we can see that output is consoled only once during the first time and every time the component gets rerendered the function doest get called. This makes the experience very fast and smooth.

Sometimes we want that computation depends upon on some value, in that case, we need to pass the arguments in the array itself as shown below

Output

In the above example, we pass the second argument increment and every time we click the button increment value gets changed and the function gets called again.

Well, that’s all, I hope I have provided a basic understanding of React useMemo hook. In the next blog, I will show how to use useReducer and useCallback for optimization, that would be more interesting. Stay tuned.

❤️ Like, Share or Leave A Comment!

If you enjoyed this post, don’t forget to give it a 👏🏼, share it with a friend you think might benefit from it and leave a comment! Stay tuned for more exciting blogs on Flutter, Elixir, React, Angular, Ruby, etc.

Thanks !!

--

--