Using PureComponent and React.memo to improve performance in React
Tags: react, javascript, typescript, webdev
Published: 2024-06-29 03:00:00

Introduction
------------

**PureComponent** in React is built on the concept of Pure Function. In this article, let's dive into **PureComponent** and the memo hook in React, as well as how to apply these tools to improve performance in React applications.

What is a Pure Function?
------------------------

First off, it's important to understand the concept of a Pure Function, which will always return the same result with the same input parameters. To put it simply, the same input will always yield the same output.

**For example:**

```ts
// this is pure function
function sum(a: number, b: number): number {
  return a+b;
}
sum(1, 2); // always return 3


const offset = 3;
// this is not pure function
function sumWithOffset(a: number, b: number): number {
  return a+b+offset;
}
sum(1, 2); // result depend on offset value
```

What is a Pure Component?
-------------------------

In React, a PureComponent is considered a component that only renders when there's a change in props or state, where the change in props or state is determined based on shallow equality checking.

Here, I'll provide two ways to create a Pure Component in React.

### 1. Class Component

Although Class Components are no longer encouraged for use in React, newer versions of React still haven't completely removed Class Components, indicating that they haven't entirely replaced Functional Components. A typical Class Component extends from **_React.Component_**, but to initialize a Pure Component, you just need to replace it with **_React.PureComponent_**.

**For example:**

```tsx
import {PureComponent} from 'react'

interface Task {
  title: string
  done: boolean
}

class MyComponent extends PureComponent<Task> {
  constructor(props: Task) {
    super(props)
  }
  render() {
    return (
      <>
        <p>Title: {props.title}</p>
        <p>Done: {props.done ? 'Yes' : 'No'}</p>
      </>
    )
  }
}
```

Here, **_MyComponent_** is defined as a PureComponent and will only render when there's a change in props or state. It's important to note that the comparison mechanism of PureComponent is **shallow equality checking**, so changing state or props can only involve assigning a new value.

  

For React components, there's a provided method called **_shouldComponentUpdate_**, which allows custom conditions for determining when a Class Component should render. Here's an example of how to use it:

```tsx
import {Component} from 'react'

class MyComponent extends Component<Task> {
  constructor(props: Task) {
    super(props)
  }

  shouldComponentUpdate(nextProps: Readonly<Task>, nextState: Readonly<{}>, nextContext: any): boolean {
    // return true to render, otherwise return false
    return true; // default value
  }

  render() {
    return (
      <>
        <p>Title: {props.title}</p>
        <p>Done: {props.done ? 'Yes' : 'No'}</p>
      </>
    )
  }
}
```

### 2. Functional Component

To create a Pure Functional Component, we use React.memo. This function takes two parameters:

1.  The component you want to make a Pure Component.
2.  Optional: a **_propsAreEqual_** callback to customize rendering.

**Here's an example:**

```tsx
import {memo, useState} from 'react'

const MyComponent = memo(
  (props: Task) => {
    return (
      <>
        <p>Title: {props.title}</p>
        <p>Done: {props.done ? 'Yes' : 'No'}</p>
      </>
    )
  },
  (prevProps, nextProps) => {
    // return false to render, otherwise true
    // reversing process with shouldComponentUpdate
  }
)
```

Here, **_React.memo_** is considered a **Higher Order Component (HOC)** with an input of a Functional Component and returns a Pure Component.

Conclusion
----------

In this article, I've introduced you to the concept and methods of initializing a **PureComponent** from both a **Class Component** and a **Functional Component**. Both approaches support custom functions that allow you to implement conditions to control the rendering of your application based on your project's needs. This is one of the simplest and most effective ways to improve performance for React applications.

**_Feel free to share your thoughts in the comments!_**

**_If you found this content helpful, please visit [the original article on my blog](https://howtodevez.blogspot.com/2024/03/using-pure-component-and-react-memo-to-improve-react-perf.html) to support the author and explore more interesting content._**

<a href="https://howtodevez.blogspot.com/2024/03/sitemap.html" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/Blogger-FF5722?style=for-the-badge&logo=blogger&logoColor=white" width="36" height="36" alt="Blogspot" /></a><a href="https://dev.to/chauhoangminhnguyen" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/dev.to-0A0A0A?style=for-the-badge&logo=dev.to&logoColor=white" width="36" height="36" alt="Dev.to" /></a><a href="https://www.facebook.com/profile.php?id=61557154776384" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/Facebook-1877F2?style=for-the-badge&logo=facebook&logoColor=white" width="36" height="36" alt="Facebook" /></a><a href="https://x.com/DavidNguyenSE" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/X-000000?style=for-the-badge&logo=x&logoColor=white" width="36" height="36" alt="X" /></a>