Blog post image

Introduction to React useMemo and how to use it

React is a set of predefined components in a Javascript framework. It is used to build User Interfaces. Developers can create large applications based on these components without reloading each page. As such, any changes in the interface are made without additional calculations and computations.

React 16.8 has introduced several hooks to improve the speed and efficiency of its applications. The hooks include useCallback, useMemo, useEffect, and others to improve the overall efficiency of a React application.

useMemo saves the output of a particular function. It accepts the memoized value of a function and its dependencies. It provides the return value by calling a function. It will only recalculate a value if there are any changes in the dependency of the function.

What Is useMemo in React?

React useMemo helps developers memoize expensive functions so that they don't have to retrieve information whenever they need to change input. The useMemo hook recomputes the specific memoized value when a user changes an input. It saves time by stopping the rerunning functions in each computation.

Memoization

The process of storing information related to expensive functions is called memoization. It is carried out by importing a useMemo hook with the function whose value you want to cache. It saves time on re-rendering components repeatedly to provide the same results.

The memoization function will save the result in the cache and reproduce it every time the component is rerendered. For example, if your function is to multiply 2*8 and the result is 16, then the useMemo will remember that the result is 16. The next time you run your function, it will not recalculate the 2*8 but simply provide you with the answer. By skipping this step the useMemo hook saves time on the computation of individual functions.

In this case, the dependencies are 2 and 8. In a static function, the multiplication sign will remain the same. However, the multiplication sign can also be a dependency if it is dynamically given to the function.

If the dependencies of a function change, then the component is rerun and recalculated. If we take the same example and change the function from 2*8 to 2*6 then the function will recalculate the dependency and give you a new result that is 12.

What useMemo is Good for?

useMemo is used to speed up slow functions in React applications. It optimizes the functions and reduces the time spent on re-rendering each computation. Here are a few ways you can implement useMemo to improve your React.js applications:

Performance Optimization In React Table

useMemo reruns the component when there are any updates in the code. As a result, it enhances the overall performance of the code. You can also improve the performance of a React Table with the help of useMemo.

  1. Use a Profiler in the React DevTool to profile all the components with multiple renderings.
  2. Implement useMemo to reduce the excessive rendering of these components.
  3. Make sure all the dependencies in the dependency array have an equal reference.

Reduce Render In Large Applications

Large applications consist of numerous renders. If a React application keeps re-rendering small computations, it will take a lot of time and reduce the performance of the application. useMemo reduces the number of child components by saving the output of these components. When you remove these child components, the application performs better and faster.

When To Use useMemo?

useMemo boosts performance optimization especially when there are specific, slow functions that are integrated into your application. Sometimes a slow function can delay the process of the whole application. useMemo can help you overcome the delay. It also provides referential equality to objects to speed up the computation.

Improve the Efficiency Of A Slow Function

The best time to use a useMemo is when the function you are calling is incredibly slow. When you import a useMemo hook with the slow function, it will re-render the result of the function.

However, you cannot use the useMemo hook in all functions, as it saves the results of computations in the cache. UseMemo increases the memory every single time you memoize a function. A new variable will be added to the code with new memoization and may cause problems in the proper running of the application.

Referential Equality

useMemo provides you with referential equality for an object. When you compare two variables in JavaScript, it will compare their references, components, and arrays. Two objects may seem equal but if the references to these objects are different they are not equal.

When you memoize an object with useMemo, the reference to the objects remains the same. As a result, the values in the object will provide the same results every time they are run. useMemo will allow the object to remain the same by keeping its reference unchanged and providing referential equality to two objects.

Implementation of useMemo

React useMemo is easy to implement. You can import it alongside a function to stop it from running the same expensive functions again and again. Here is an example of the change in the theme of a website from dark to light. The following function illustrates the theme without useMemo, and even though it is not heavy it illustrates how useMemo can be used. Often useMemo is used when calculating chart data for example. So instead of saving chart data to a state, it will be saved in a variable using useMemo, but for the sake of simplicity, we chose to use a light and dark theme example.

Before importing the useMemo, the function could look like this,

import React, {useState, useEffect} from ‘react’;

export default function App() {
   const [chosenTheme, setChosenTheme] = useState("Light");

   useEffect(() => {
      const themeVariable = themeValueFromCookie;
      if (themeVariable == "Light") {
         setChosenTheme("Light");
      } else {
         setChosenTheme("Dark");
      }
   }, [themeValueFromCookie]);
}

At this stage, the application calculates the computations every time the code is run. As a result, the theme of the page will change from light to dark after a few seconds. This delay will impact the display of the application every time.

useMemo can help reduce time by saving the output and producing the result in an instance. If we want to make the change in theme instantaneous, we can implement the hook useMemo in the function. The function will look like this,

import React, {useState, useMemo} from ‘react’;

export default function App() {

   const chosenTheme = useMemo(() => {
      const themeVariable = themeValueFromCookie;
      if (themeVariable == "Light") {
         return "Light";
      } else {
         return "Dark";
      }
   }, [themeValueFromCookie]);
}

When you import the useMemo into the function, the theme will change from light to dark instantaneously.

Conclusion

React useMemo is a built-in hook that helps speed up the process of running functions in a React application. Developers write code without the useMemo hook and see if all the functions are working properly. If there are excessive computations in the code then we can use the useMemo hook. It saves the output of the function and provides the results instantly. It works as an optimization tool to reduce run time on applications, overcome slow functions and maintain referential equality in objects.

Author

Join our newsletter

Join our monthly newsletter and receive news about Sustainable WWW, information about interesting articles, events and podcasts.