boy-Over-9
== write & share ==

Maximizing Performance in React - When to Use Component and PureComponent

January 11, 2023

Component and PureComponent in reactjs

React provides two types of components for building UI - Component and PureComponent.

A Component is a basic building block of a React application. It provides a way to describe UI and the behavior that accompanies it. When you extend React.Component, you define a class-based component that implements a render method, which returns a tree of components. When a component is rendered, its render method is executed, and the resulting tree of components is converted to HTML elements.

A PureComponent is a Component that implements shouldComponentUpdate. The shouldComponentUpdate method is used to determine whether a component should be re-rendered or not. If the method returns false, the component will not be re-rendered. This can be useful for performance optimization when you have a large number of components and the cost of rendering is high.

The main difference between Component and PureComponent is that PureComponent implements shouldComponentUpdate with a shallow comparison of the props and state, while the Component does not. If your component only changes its own state or props, it is safe to use a PureComponent. But, if you are making API calls, or changing data that is not contained in the props or state, you should use Component.

In summary, use PureComponent if you want to optimize performance by avoiding unnecessary re-renders and you are sure that the props and state changes are only affecting the component. Use Component if you have complex logic, API calls, or data changes that could affect other components.

When to use components and not purecomponent?

You should use a Component when:

1. You have complex logic: If your component has complex logic that involves calculations or data manipulation, you should use a Component instead of a PureComponent.

2. You are making API calls: If your component needs to make API calls or retrieve data from an external source, you should use a Component.

3. You are changing data that is not contained in the props or state: If your component changes data that is not contained in the props or state, such as global data, you should use a Component.

4. You have child components that are updated frequently: If your component has child components that are updated frequently, you should use a Component to ensure that the parent component is also re-rendered.

It is important to note that using a Component instead of a PureComponent will result in more frequent re-renders, which can negatively impact the performance of your application. You should use a PureComponent when:

  1. You want to optimize performance: If you have a large number of components and the cost of rendering is high, you can use a PureComponent to avoid unnecessary re-renders.

  2. The component only changes its own state or props: If the component only changes its own state or props, it is safe to use a PureComponent.

In summary, use Component when you have complex logic, API calls, or data changes that could affect other components. Use PureComponent if you want to optimize performance by avoiding unnecessary re-renders and you are sure that the props and state changes are only affecting the component.

Example

Example of using Component:

import React, { Component } from 'react'

class UserList extends Component {
  state = {
    users: [],
    loading: true,
  }

  componentDidMount() {
    // Fetching data from an API
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((users) => {
        this.setState({ users, loading: false })
      })
  }

  handleUserUpdate = (userId, updates) => {
    // Updating user data
    const { users } = this.state
    const updatedUsers = users.map((user) => {
      if (user.id === userId) {
        return { ...user, ...updates }
      }
      return user
    })
    this.setState({ users: updatedUsers })
  }

  render() {
    const { users, loading } = this.state
    return (
      <div>
        {loading ? (
          <p>Loading...</p>
        ) : (
          <ul>
            {users.map((user) => (
              <li key={user.id}>
                {user.name} ({user.email})
                <button
                  onClick={() =>
                    this.handleUserUpdate(user.id, { isAdmin: !user.isAdmin })
                  }
                >
                  Toggle Admin
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>
    )
  }
}

export default UserList

Example of using PureComponent:

import React, { PureComponent } from 'react'

class UserCard extends PureComponent {
  render() {
    const { user } = this.props
    return (
      <div>
        <h3>{user.name}</h3>
        <p>{user.email}</p>
      </div>
    )
  }
}

export default UserCard

Profile picture

written by boy-Over-9
Eat, sleep, code, Judo repeat... Twitter