The Wayback Machine - https://web.archive.org/web/20241104092819/https://www.geeksforgeeks.org/reactjs-shouldcomponentupdate-method/
Open In App

ReactJS shouldComponentUpdate() Method

Last Updated : 10 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The shouldComponentUpdate method allows us to exit the complex react update life cycle to avoid calling it again and again on every re-render. It only updates the component if the props passed to it changes.

The shouldComponentUpdate method is majorly used for optimizing the performance and to increase the responsiveness of the website but do not rely on it to prevent rendering as it may lead to bugs. The shouldComponentUpdate method is crucial for optimizing performance in class components. The ReactJS Course explains how to use this method effectively to prevent unnecessary re-renders.

Syntax:

shouldComponentUpdate(nextProps, nextState)

Return value: It by default it returns true and if it returns false then render(), componentWillUpdate() and componentDidUpdate() method does not gets invoked.

Example: In this example, we are going to build a counter application which only renders when its props value is changed.

App.js

JavaScript
import React, { useState } from "react";
import Counter1 from "./Counter1";
import Counter2 from "./Counter2";


const App = () => {

// Using useState hooks for defining state
  const [counter1, setCounter1] = useState(0);

  const increase1 = () => {
    setCounter1(counter1 + 1);
  };
  const [counter2, setCounter2] = useState(0);

  const increase2 = () => {
    setCounter2(counter2 + 1);
  };
  
  return (
    <div className="container">
      <div>
        <Counter1 value={counter1} onClick={increase1} />
      </div>
      <div>
        <Counter2 value={counter2} onClick={increase2} />
      </div>
    </div>
  );
};

export default App;

Without using shouldComponentUpdate() method:

Counter1.js JavaScript

</p><pre><code class="language-javascript"></code></pre><p></p><pre><code><span>import React, { Component } from "react";</span></code><br><br><code><span>class Counter1 extends Component {</span></code><br><code><span>  render() {</span></code><br><code><span>    console.log("Counter 1 is calling");</span></code><br><code><span>    return (</span></code><br><code><span>      <div></span></code><br><code><span>        <h2>Counter 1:</h2></span></code><br><code><span>        <h3>{this.props.value}</h3></span></code><br><code><span>        <button onClick={this.props.onClick}>Add</button></span></code><br><code><span>      </div></span></code><br><code><span>    );</span></code><br><code><span>  }</span></code><br><code><span>}</span></code><br><br><code><span>export default Counter1;</span></code></pre><p dir="ltr"><br></p><p dir="ltr"><b><strong>Counter2.js</strong></b><gfg-tabs data-run-ide="false" data-mode="light"><gfg-tab slot="tab">JavaScript

import React, { Component } from "react";

class Counter2 extends Component {
render() {
console.log("Counter 2 is calling");
return (
<div>
<h2>Counter 2:</h2>
<h3>{this.props.value}</h3>
<button onClick={this.props.onClick}>Add</button>
</div>
);
}
}

export default Counter2;


Output:

With using shouldComponentUpdate() Method:

Counter1.js JavaScript

</p><pre><code class="language-javascript"></code></pre><p></p><pre><code><span>import React, { Component } from "react";</span></code><br><br><code><span>class Counter1 extends Component {</span></code><br><code><span>  shouldComponentUpdate(nextProps) {</span></code><br><code><span>    // Rendering the component only if </span></code><br><code><span>    // passed props value is changed</span></code><br><br><code><span>    if (nextProps.value !== this.props.value) {</span></code><br><code><span>      return true;</span></code><br><code><span>    } else {</span></code><br><code><span>      return false;</span></code><br><code><span>    }</span></code><br><code><span>  }</span></code><br><code><span>  render() {</span></code><br><code><span>    console.log("Counter 1 is calling");</span></code><br><code><span>    return (</span></code><br><code><span>      <div></span></code><br><code><span>        <h2>Counter 1:</h2></span></code><br><code><span>        <h3>{this.props.value}</h3></span></code><br><code><span>        <button onClick={this.props.onClick}>Add</button></span></code><br><code><span>      </div></span></code><br><code><span>    );</span></code><br><code><span>  }</span></code><br><code><span>}</span></code><br><br><code><span>export default Counter1;</span></code><br></pre><p dir="ltr"><br></p><p dir="ltr"><b><strong>Counter2.js</strong></b><gfg-tabs data-run-ide="false" data-mode="light"><gfg-tab slot="tab">JavaScript

import React, { Component } from "react";

class Counter2 extends Component {
shouldComponentUpdate (nextProps) {
// Rendering the component only if
// passed props value is changed

if (nextProps.value !== this.props.value) {
return true;
} else {
return false;
}
}
render() {
console.log("Counter 2 is calling");
return (
<div>
<h2>Counter 2:</h2>
<h3>{this.props.value}</h3>
<button onClick={this.props.onClick}>Add</button>
</div>
);
}
}

export default Counter2;


Output:



Similar Reads

What does "shouldComponentUpdate" do and why is it important ?
The shouldComponentUpdate is a lifecycle method in React. The shouldComponentUpdate() is invoked before rendering an already mounted component when new props or states are being received. Prerequisites:NPM & Node.jsReact JS shouldComponentUpdate()React JS React JS Lifecycle methodsWhat Does "shouldComponentUpdate" do?:This method makes the comp
3 min read
ReactJS getDerivedStateFromError() Method
The getDerivedStateFromError() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the render phase, so side-effects are not permitted in this method. For side-effects, use component
2 min read
ReactJS componentDidCatch() Method
The componentDidCatch() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the commit phase, so unlike getDerivedStateFromError() which was called during the render phase, side-effe
2 min read
ReactJS UNSAFE_componentWillMount() Method
The componentWillMount() method invokes right before our React component gets loaded or mounted in the DOM (Document Object Model). It is called during the mounting phase of the React Life-cycle, i.e., before render(). It is used to fetch data from outside the component by executing the React code synchronously which causes our component to render
3 min read
ReactJS unmountComponentAtNode() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us with some in-built methods that we can override at particular stages in the life-cycle of the component. In class-based components, the unmountComponentAtNode() method Remove a mounted React component from the DOM. Creati
1 min read
ReactJS isElement() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use isElement() method. The isElement() method returns true if an element is any rea
2 min read
ReactJS isCompositeComponent() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will see how to use isCompositeComponent() method. The isCompositeComponent() method return true if i
2 min read
ReactJS isElementOfType() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use isElementOfType() method. The isElementOfType() method return true if an element
2 min read
ReactJS isCompositeComponentWithType() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use isCompositeComponentWithType() method. This method returns true if a component w
2 min read
ReactJS isDOMComponent() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use isDOMComponent() method. This method returns true if the instance is a DOM compo
2 min read
ReactJS TestRenderer.toTree() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use TestRenderer.toTree() method. This method is used to return an object representi
2 min read
ReactJS TestRenderer.toJSON() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use TestRenderer.toJSON() method. This method is used to return an object representi
2 min read
ReactJS TestRenderer.create() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use TestRenderer.create() method. This method is used to create a TestRenderer insta
2 min read
ReactJS TestRenderer.unmount() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use TestRenderer.unmount() method. TestRenderer.unmount() method is used to unmount
1 min read
ReactJS testInstance.findAllTypes() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use testInstance.findAllTypes() method. The testInstance.findAllTypes() method is us
1 min read
ReactJS testInstance.findByProps() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use testInstance.findByProps() method. The testInstance.findByProps() method is used
1 min read
ReactJS testInstance.findAllByProps() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use testInstance.findAllByProps() method testInstance.findAllByProps() method is use
1 min read
What is ComponentWillMount() method in ReactJS ?
ReactJS requires several components to represent a unit of logic for specific functionality. The componentWillMount lifecycle method is an ideal choice when it comes to updating business logic, app configuration updates, and API calls. PrerequisitesReact JSReact JS class componentsComponentWillMount() methodThe componentWillMount() lifecycle hook i
4 min read
How re-render a component without using setState() method in ReactJS ?
In React, to re-render a class-based component with an updated state we generally use the setState() method. But instead, we can use other methods to re-render a component without using setState(). Prerequisites: NPM & Node.jsReact JSReactJS propsReactJS forceUpdate() methodApproaches to re-render a component without using setState() method are
3 min read
How The ReactJS onClick Can't Pass Value To Method?
In React, handling events like onClick is a common task, often requiring passing values to event handlers. However, developers sometimes encounter issues where the onClick event handler can't seem to pass values to the method. Understanding why this happens and how to handle it properly is essential for effective react development. When you attach
3 min read
ReactJS UNSAFE_componentWillUpdate() Method
The componentWillUpdate() method provides us the control to manipulate our React component just before it receives new props or state values. It is called just before the rendering of our component during the updating phase of the React Life-cycle ,i.e., this method gets triggered after the updation of State or Props and just before the execution o
3 min read
ReactJS UNSAFE_componentWillReceiveProps() Method
The componentWillReceiveProps() is invoked before our mounted React component receives new props. It is called during the updating phase of the React Life-cycle. It is used to update the state in response to some changes in our props. We can't call this with initial props during mounting because React calls this method only when our component's pro
3 min read
ReactJS getSnapshotBeforeUpdate() Method
The getSnapshotBeforeUpdate() method is invoked just before the DOM is being rendered. It is used to store the previous values of the state after the DOM is updated. Syntax:getSnapshotBeforeUpdate(prevProps, prevState)Parameters: It accepts two parameters, they are prevProps and prevState which are just the props or state before the component in qu
2 min read
ReactJS componentWillUnmount() Method
In React, lifecycle methods allow you to manage the behaviour of components at different stages of their existence. One important lifecycle method for cleaning up resources and side effects is componentWillUnmount(). This method is called just before a component is removed from the DOM, making it an essential tool for avoiding memory leaks and ensu
3 min read
ReactJS findDOMNode() Method
findDOMNode in React is used to directly access a component's underlying DOM node. It is mainly used in class components for DOM manipulation, animations, or integration with third-party libraries. It's considered unsafe in modern React development. Syntax:ReactDOM.findDOMNode(component)Parameters: component: The component can be either a React com
2 min read
ReactJS componentDidMount() Method
The componentDidMount method in react is used to execute some code immediately after mounting. This is a lifecycle method in React class component that is called only once when the component is mounted in the DOM. This method helps to execute when the component is rendered on the page. Syntax:componentDidMount(){ // code to execute}All the AJAX req
2 min read
ReactJS forceUpdate() Method
The components in React will re-render only if the state of the component or the props passed to it changes but if we need to re-render the component if some data changes then we will use forceUpdate() method of React. Calling the forceUpdate() will forcibly re-render the component and thus calls the render() method of the component skipping the sh
2 min read
ReactJS bind() Method
The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component. Syntax:this.function.bind(this,[arg1...]);Parameter:It accepts two parameters, the first parameter is the this: keyword used for binding [arg1...]: the sequence of arguments that are passed as a parameter and are optiona
2 min read
ReactJS componentDidUpdate() Method
React primarily focuses on building single-page applications where components dynamically update as the state or props change. Among the various lifecycle methods that React provides, the componentDidUpdate() method is important in handling updates and performing side effects after a component has been re-rendered. In this article, we will explore
3 min read
ReactJS Onsen UI AlertDialogButton Component
ReactJS Onsen-UI is a popular front-end library with a set of React components that are designed to developing HTML5 hybrid and mobile web apps in a beautiful and efficient way. AlertDialogButton Component denote each button of the alert dialog. We can use the following approach in ReactJS to use the Onsen-UI AlertDialogButton Component. AlertDialo
2 min read
Article Tags :
three90RightbarBannerImg