1.

How to prevent re-renders in React?

Answer»
  • Reason for re-renders in React:
    • Re-rendering of a COMPONENT and its child components occur when props or the 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:
<P>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> );}}
  • The Parent component is the parent component and the 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 components, 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. 



Discussion

No Comment Found