useMemo Hook in React
How to optimize performance with
React 16.8 introduced the concepts of hooks. One of the hooks added to React is
useMemo. It’s used to optimize the performance of a React application.
If you need background information on hooks in React, read this first:
Hooks seem to be a fantastic addition to React since they direct developers’ focus back to functional programming practices.
useMemo enables memoization in React hook functions. Memoization is a programming strategy where the function remembers the output of previous executions and uses it for further executions.
Why use useMemo Hooks?
The basic usage of this hook is to improve the performance of React applications by memoizing the output and related input parameters of commonly used functions.
If the memoized function is called again with the same parameters, it doesn’t re-execute the function. Rather, the initial cached value is returned from the function, reducing the overhead of executing the same function again.
For example, here’s a problem statement that needs to be resolved:
In the code above, the value of
count is updated every second. Update to the
count variable leads to the re-rendering of the component. Every time the component is re-rendered, we’re calling the function
returnValue with the same parameter. It executes every second, returns the same value, and the component is updated with the value.
When a function takes the same parameter each time, it returns the same output every time. So we’re wasting lots of effort on recalculation.
We expect these functions to be pure so that the function does not depend on nor modify states outside their scope. The output of the function is only dependent on the input parameters. And if the function is called multiple times with the same input parameters, the same output will be returned.
The problem with the above code is that every time we use the same parameter to invoke the function
returnValue we get the same result. We can incorporate a mechanism to reuse the value from the previous execution.
useMemo hook enables us to memoize the result of the execution of a function with a given set of parameters. Next time the function is called with the same parameter, we can return the data that has been cached, rather than re-executing the entire function.
In the code above, we are using
useMemo to memoize the output received from the execution of the
returnValue function. Initially, we call this function with
10 as a parameter. Next time the component is re-rendered, the value of the
calculatedValue variable needs to be re-calculated. We’re using the
useMemo function to memoize the output from the previous execution with the given input parameter.
Since the parameter passed the last time is the same as the parameter for the next execution, the memoized data is received rather than getting data from the re-execution of the given function. Hence
useMemo hooks are able to contribute to the performance of the application.