Introduction

Memoization is one of the performance optimization techniques that aims to speed up the render process of components. In this article, we are going to explore what is Memoization and how to implement Memoization in React applications.

Memoization in React

When can use Memoization

When shouldn't use Memoization

Example

I have created a simple application with three components which are App, Counter1, and Counter2.

In the App component, render the Counter1 and Counter2 components passing the state value as props. Pass the count1 state value to the Counter1 component and the count2 state value to the Counter2 component. Just display those values in the corresponding components.

render() {
    return (
      <>
        <Counter1 Count={this.state.count1} />
        <br />
        <Counter2 Count={this.state.count2} />
        <br />
        <button onClick={this.onClick}>Increment</button>
      </>
    );
}
// Counter1.js

import React from "react";

const Counter1 = (props) => {

  console.log("Counter1 Component Rendering");
  return (
    <>
      <h1>Counter1 Component</h1>
      {props.Count}
    </>
  );
}

export default Counter1;
​// Counter2.js

import React from "react";

const Counter2 = (props) => {

  console.log("Counter2 Component Rendering");
  return (
    <>
      <h1>Counter2 Component</h1>
      {props.Count}
    </>
  );
}

export default Counter2;

I have created one button called "Increment" in the App component and increment the count2 state value on the button click event(onClick).

onClick() {
	let count = this.state.count2;
	this.setState({ count2: count + 1 });
}

Without Memoization

When I clicked the button, the count2 value will increment and the Counter2 component will be updated with the latest value (the Counter2 component will re-render). The expected thing is only the Counter2 component should re-render. But the Counter1 component also getting re-rendered with the Counter2 component. Because of the updating of state value in the App component. Even there is no change in count1 state value, the Counter1 component getting re-rendered.

With Memoization

The expected thing is If I click the button then, only both the count2 value and Counter2 component will be updated and the Counter1 component should be idle. We can achieve it by adding the Memoization to the Counter1 component. I have added React.memo to the Counter1 component. React.memo will prevent re-rendering the Counter1 component if there are no changes in Counter1 component props. Now, the Counter1 component won't re-render whenever clicks the button.

// Counter1.js
import React from "react";
const Counter1 = (props) => {
  console.log("Counter1 Component Rendering");
  return (
    <>
      <h1>Counter1 Component</h1>
      {props.Count}
    </>
  );
}
export default React.memo(Counter1); // Added Memoization

Summary

I hope you have liked it and know about Memoization and how to implement it in React applications.