0 votes
by
How to prevent re-renders in React?

1 Answer

0 votes
by

Reason for re-renders in React:

Re-rendering of a component and it’s child components occur when props or state of the component has been changed.

Re-rendering components that are not updated, affects the performance of an application.

How to prevent re-rendering:

Consider the following components:

class Parent extends React.Component {

 state = { messageDisplayed: false };

 componentDidMount() {

   this.setState({ messageDisplayed: true });

 }

 render() {

   console.log("Parent is getting rendered");

   return (

     <div className="App">

       <Message />

     </div>

   );

 }

}

class Message extends React.Component {

 constructor(props) {

   super(props);

   this.state = { message: "Hello, this is vivek" };

 }  

 render() {

   console.log("Message is getting rendered");

   return (

     <div>

       <p>{this.state.message}</p>

     </div>

   );

 }

}

Parent component is the parent component and Message is the child component. Any change in the parent component will lead to re-rendering of the child component as well.

To prevent the re-rendering of child component, we use the shouldComponentUpdate( ) method:

**Note- Use shouldComponentUpdate( ) method only when you are sure that it’s a static component.

class Message extends React.Component {

 constructor(props) {

   super(props);

   this.state = { message: "Hello, this is vivek" };

 }

 shouldComponentUpdate() {

   console.log("Does not get rendered");

   return false;

 }

 render() {

   console.log("Message is getting rendered");

   return (

     <div>

       <p>{this.state.message}</p>

     </div>

   );

 }

}

As one can see in the code above, we have returned false from the shouldComponentUpdate( ) method, which prevents the child component from re-rendering.

...