DEV Community

Cover image for Memoizing React components
Raushan Sharma
Raushan Sharma

Posted on • Updated on

Memoizing React components

Alright what is Memoization first?

In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

In other words, Memoization is a way to lower a function's time cost in exchange for space cost; that is, memoized functions become optimized for speed in exchange for a higher use of computer memory space.

If you see the diagram below, a function named sum is getting called multiple times. Even though the function is called with the same parameters 1,2 it has to re-calculate the result.

A diagram image that illustrate a function being called multiple times

Well, wouldn't it be nice if we put the already calculated result and store somewhere in memory against the parameters passed while each call. This way we can return directly from the memory if we observe that the result for the passed parameter was already calculated?

BLACK GUY THINKING MEME

Have a look at below function call diagram, you can see that the result is directly being return from memory when we are calling memoSum(1,2) for the second time with same parameters 1,2.

A diagram image that shows a memoized function getting called multiple times

This is pretty much fine to have a function without memoization if we are considering a function which is not CPU intensive, but however, if you consider a pure function which is very frequently called, and takes considerable amount of time to return the results, it's better to memoize the function, so that already computed results can be used instead of computing again and again for the same parameters.

Always remember that only pure functions can be memoized. If you don't have a clue about what makes a function pure, you might want to follow the following article written by ysael pepin which explains on of the most basic concepts of functional programming - https://dev.to/ysael/functional-programming-basics-part-1-pure-function-e55

How can we memoize a given pure function?

Well there are bunch of libraries available which has already implemented memoization and made it available different API's for that.

Lodash is one of the JavaScript libraries that provides memoize function to solve this problem.

const lodash = require('lodash'); const add = function(a, b){return a + b}; const memoizedAdd = lodash.memoize(add); console.log('1 + 1', memoizedAdd(1,1)); // This will return the memoized result console.log('1 + 1', memoizedAdd(1,1));

But what memoization has to do with React components?

As we already know that a React component is just like another JavaScript function that returns bunch of HTML tags, that we call JSX and the parameters passed to this very function is called Props.

Image contains a meme that says - If it walks like a duck and quacks like a duck then it must be a duck

Yes your guess is right, we can definitely memoize a React component.

Memoizing a React Component with React.memo

const MemoizedComponent = React.memo(function MyComponent(props) {
  /* render using props */
});

Enter fullscreen mode Exit fullscreen mode

React.memo is a higher order component. It’s similar to what React.PureComponent does, but for functional components.

If your function component renders the same result given the same props, you can wrap it in a call to React.memo() for a speedy rendering in some cases by memoizing the result. This means that React will skip rendering process for the component and doesn't perform a virtual DOM difference check, it will just re-use the last rendered result.

export function PassengerDetails({ passengerName, departureDate }) {
  return (
    <div>
      <div>Passenger: {passengerName}</div>
      <div>Departure: {departureDate}</div>
    </div>
  );
}

export const MemoPassengerDetails = React.memo(PassengerDetails);

Enter fullscreen mode Exit fullscreen mode

By default it will only shallowly compare complex objects in the props object.

If you want control over the comparison, you can also provide a custom comparison function as the second argument.


export function PassengerDetails({ passengerName, departureDate }) {
  return (
    <div>
      <div>Passenger: {passengerName}</div>
      <div>Departure: {departureDate}</div>
    </div>
  );
}


function areEqual(prevProps, nextProps) {
  /*
  return true if passing nextProps to render would return
  the same result as passing prevProps to render,
  otherwise return false
  */
}

export default React.memo(PassengerDetails, areEqual);

Enter fullscreen mode Exit fullscreen mode

Limitations

  1. To be able to memoize, the function must be a pure function.
  2. Where space is critical than computation time, you might not need to memoize you function.
  3. When you function is less frequently executed, there's no much benefit of memoizing the function.

Things to remember

  1. Instead of Lodash's memoize use React.memo to memoize React components as the later one is more optimized to work with React components.
  2. React.memo only compare props shallowly, if you want to deep compare the props then it's better to pass your own compare function as a second parameter in React.memo function.
  3. Do not get confused React.memo with useMemo, you can learn about useMemo which is explained well by Linas Spukas in the following article - https://dev.to/spukas/react-usememo-for-optimisation-5gna

If you find the article informative, please don't forget to follow.

Happy coding :)

Interested in having a look at my other articles?
Learn some of the best practices in web accessibility that will help your web content or web application reach out to a broader audience.

Learn how code splitting is a thing that you have been missing.

Find out how Optional chaining and Nullish coalescing can make your code look more clean and readable.

Top comments (3)

Collapse
 
arminder_singh profile image
Arminder singh

Let's remind react to remember components

Collapse
 
thayannevls profile image
Thayanne Luiza

Awesome!

Collapse
 
sagar profile image
Sagar

nice post

thanks man