Components Lifecycle

React shouldComponentUpdate Method | Components Lifecycle

The shouldComponentUpdate Method -
The shouldComponentUpdate() method is invoked before rendering (render method) when new props or state are being received.

The defaults value is true.

The shouldComponentUpdate() method is not called for the initial render or when forceUpdate() is used.

Explore to Understand  - React Lifecycle Components

As an Example 1–

When shouldComponentUpdate value is fale? My Color is red after click on Change color.

import React from 'react';
import ReactDOM from 'react-dom';

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {color: "red"};
  }
  shouldComponentUpdate() {
    return false;
  }
  changeColor = () => {
    this.setState({color: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Color is {this.state.color}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />document.getElementById('root'));


Result of this example is – My color is red


As an Example 2–

When shouldComponentUpdate value is true? My Color is blue after click on Change color.

import React from 'react';
import ReactDOM from 'react-dom';

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {color: "red"};
  }

  shouldComponentUpdate() {
    return true;
  }

  changeColor = () => {
    this.setState({color: "blue"});
  }

  render() {
    return (
      <div>
      <h1>My Color is {this.state.color}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />document.getElementById('root'));


Result of this example is – My color is blue
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^