useMemo is a React hook that returns the memoized value of some computation.
Memoization is a method to save the results of function execution to prevent repeated calculations. This optimization is used to increase the speed of your application.
useMemo executes in 2 cases:
Array of dependencies has changed
Let’s look at an example of how you can apply it to your ReactJS application:
This optimization helps to avoid expensive computations with every rendering.
One of the biggest mistakes I often see is NO debounce function.
Are you serious?
Debounce function is needed to ensure that a particular task is not run too often and not decreasing browser performance.
How does it work?
Debounce returns a function, that will not be triggered as long as it continues to be invoked. Returned function will be called after it stops being called for N milliseconds.
Let’s see how it works inside:
And now let’s do the real-life optimization.
For example, you have an input that sent search value on every change to the server:
sendSearchValueToServer fires on every input change. It’s a lot of API requests, let’s optimize it with
Now you see how important debounce is?
And you may not even feel that the app is “getting slower”. But it’s a compound effect, the larger your app the slower it gets.
What’s the problem?
Arrow function will create a new instance of the function on each render. It’s a bad practice that hurts performance because the function is recreated on each render. This creates a lot of work for the garbage collector and rerendering many elements might create jank in animations.
How to fix it?
Let’s look at an example:
Now you know 3 methods to optimize your React application.
Hope that can help you 🙏
If you like this article share it with your friends!
That’s all. Thanks!