Memoizing React components
Tags: react, memo, javascript, optimization
Published: 2020-02-02 22:48:49

---
title: Memoizing React components
published: true
description: How to memoize your react component for better performance
tags: react, memo, javascript, optimization
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/zyidc1q00z8uhi0onu06.png
---

### 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](https://dev-to-uploads.s3.amazonaws.com/i/zkcea3j1v4bu7untm3mh.png)

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](https://dev-to-uploads.s3.amazonaws.com/i/1o2gh3eruoudbivy9el4.jpg)

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](https://dev-to-uploads.s3.amazonaws.com/i/pgkvdslbwsnvo8n1lpds.png)

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](https://dev.to/ysael/functional-programming-basics-part-1-pure-function-e55) 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](https://dev.to/ysael/functional-programming-basics-part-1-pure-function-e55) 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`](https://dev.to/ysael) 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](https://lodash.com/) is one of the JavaScript libraries that provides [`memoize`](https://lodash.com/docs/4.17.15#memoize) function to solve this problem.

{% runkit %}
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));

{% endrunkit %}

### 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](https://reactjs.org/docs/introducing-jsx.html) 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](https://dev-to-uploads.s3.amazonaws.com/i/8wz8p0g8e3k4nn74zkfz.png)


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

### Memoizing a React Component with React.memo 


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

```

React.memo is a [higher order component](https://reactjs.org/docs/higher-order-components.html). It’s similar to what [React.PureComponent](https://reactjs.org/docs/react-api.html#reactpurecomponent) 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.



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

export const MemoPassengerDetails = React.memo(PassengerDetails);

```


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. 


```javascript

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);

```
### Limitations
1. To be able to memoize, the function must be a [pure function](https://dev.to/ysael/functional-programming-basics-part-1-pure-function-e55).
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`](https://reactjs.org/docs/hooks-reference.html#usememo), you can learn about `useMemo` which is explained well by [`Linas Spukas`](https://dev.to/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.
{% post https://dev.to/redraushan/accessibility-mantras-for-web-developers-2m76 %}

Learn how code splitting is a thing that you have been missing.
{% post https://dev.to/redraushan/route-based-code-splitting-in-reactjs-28ah %}

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

{% post https://dev.to/redraushan/javascript-optional-chaining-nullish-coalescing-48o5 %}