learn react ui logoLearnReactUI
Controlling re-renders on React Class Components

How to control re-renders on React Class Components

In React class components, you have several options for controlling renders and optimizing the performance of your application. By utilizing the lifecycle methods provided by React, you can have more control over when and how your components re-render.

One of the key lifecycle methods to control renders is shouldComponentUpdate. By overriding this method, you can determine whether the component should re-render or not. By default, shouldComponentUpdate returns true, indicating that the component should always re-render. However, you can implement custom logic inside this method to optimize rendering. For example, you can check if the component's props or state have changed and conditionally decide whether to trigger a re-render or not. By selectively re-rendering only when necessary, you can improve the performance of your application.

class ExampleComponent extends React.Component {
  state = {
    count: 0,
  };

  shouldComponentUpdate(nextProps, nextState) {
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
  }

  handleClick = () => {
    this.setState((prevState) => ({
      count: prevState.count + 1,
    }));
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleClick}>Increment</button>
      </div>
    );
  }
}

In this example, the ExampleComponent class has a count state property. The shouldComponentUpdate method is overridden to compare the current count state with the next count state. If they are different, the component will re-render; otherwise, it will not. By doing this, we optimize rendering and prevent unnecessary re-renders when the count state has not changed.

Another important lifecycle method is componentDidUpdate. This method is called after the component has updated and re-rendered. It provides an opportunity to perform side effects or additional operations based on the updated props or state. For example, you can make API calls, update the DOM, or trigger animations based on the changes in the component's data. However, it's crucial to be cautious and avoid infinite loops by checking if the component's props or state have actually changed before performing any actions inside componentDidUpdate.

It's worth mentioning that the componentWillReceiveProps method, which was previously used to handle prop changes, is now deprecated and will be removed in future versions of React. Instead, it is recommended to use componentDidUpdate to handle prop changes. By doing so, you can ensure consistency in your codebase and stay up to date with the latest best practices.

By leveraging these lifecycle methods, you can gain more control over the rendering process of your React class components. This allows you to optimize performance by selectively re-rendering components only when necessary, improving the overall user experience of your application.

React provides a PureComponent class that can be used as a base class for your components. PureComponent implements the shouldComponentUpdate method with a shallow props and state comparison. This means that if the props and state of a PureComponent have not changed, it will not re-render.

class ExampleComponent extends React.PureComponent {
  state = {
    count: 0,
  };

  handleClick = () => {
    this.setState((prevState) => ({
      count: prevState.count + 1,
    }));
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleClick}>Increment</button>
      </div>
    );
  }
}

In the above example, ExampleComponent extends React.PureComponent instead of React.Component. This ensures that the component only re-renders when the count state changes, optimizing rendering and improving performance.

It's important to note that PureComponent performs a shallow comparison of props and state. If your component's props or state contain complex objects or arrays, you should be cautious and ensure that the comparison is accurate. In some cases, you might need to implement custom logic in shouldComponentUpdate instead of using PureComponent.

Using PureComponent is an effective way to optimize rendering in class components by reducing unnecessary re-renders. However, it's important to evaluate whether it is suitable for your specific use case and to test the performance impact of using PureComponent compared to manually implementing shouldComponentUpdate.

To further optimize rendering in React class components, you can also use the React.memo higher-order component (HOC). By wrapping your component with React.memo, you can memoize the component and prevent unnecessary re-renders. React.memo performs a shallow comparison of the component's props and only re-renders if the props have changed. This can be especially useful when dealing with large or complex components that receive frequent updates to their props. By memoizing these components, you can significantly improve the performance of your application.

In below example (https://onurdayibasi.dev/rerender-with-state)

In this part, we showcase a container component equipped with a counter state and a corresponding button that increments this state. Our focus lies on meticulous testing to determine whether the components below will re-render. The expectation is set: none of the sub-components should re-render, given that none of them directly utilize the state(counter) housed within the parent container

demo.png

Let's first examine our components. We have components grouped into three categories. In the first group, there are no additional re-render prevention structures on class components. We call these Normal State Components Group

  • No State and Props Comp
  • Age Class Comp

In the second group, we have components where shouldComponentUpdate and PureComponent structures have been implemented to enhance their efficiency.

  • Age Class ShouldUpdate Comp
  • Age Class Pure Comp

In the third section, there is a group of React components where the React Memo has been

  • No State and Props Comp
  • Age Class Comp

Now, let's increment the Parent Container counter by 1 and observe its impact on the respective components. You can check which components are re-rendered in the adjacent console area.

console.png

As evident in the above image, only the components in the first group, where we haven't added any performance-enhancing capabilities upon changes in the Parent Container state, were affected.

If you click on the "IncreaseAge" button in the components, you will observe that only the relevant component is rendered.

You may get the source code to better understand how it works by clicking on the adjacent download button.