1.

What are Pure Components in React?

Answer»

Pure Component are special type of Components in React, which doesn’t re-render itself if the state is not changed. In ReactJS if we do a this.setState, it re-renders the Component and it’s child components.

Consider the below example. The initial state VALUE is 1. It has a “componentDidMount” by which we are simulating AJAX call by running a setInterval, every 2 seconds. It has a this.setState, but sets the value again to 1. But because this.setState runs, it re-render the component.

import React from ‘react’; class PureDemo extends React.Component {  constructor(props) {    super(props)    this.state={     value: 1    }  }   componentDidMount() {    setInterval(() => {      this.setState({ value: 1})     }, 2000)   }    render() {  console.log('Render PureDemo');    return (      <Demo value={this.state.value} />    )  } } const Demo = (props) => {  console.log('Render Demo'); return <div>{props.val}</div> } ReactDOM.render(<PureDemo />, document.querySelector("#app"))

If we run the below, both components will be rendered after every 2 seconds and we will get the below printed in the console.

Now, we can solve this ISSUE of not rendering components if state is not changed, by using lifecycle hook shouldComponentUpdate. It will run in each render and here we are CHECKING if the CURRENT state is equal to the next state. If they are equal, we are returning FALSE and the components will not re-render.

class PureDemo extends React.Component {  constructor(props) {    super(props)    this.state={     value: 1    }  }  componentDidMount() {   setInterval(() => {     this.setState({ value: 1})    }, 2000)  }  shouldComponentUpdate(nextProp, nextState) {     return (this.state.value === nextState.value ? false : true )   }   render() {  console.log('Render PureDemo');    return (      <Demo value={this.state.value} />    )  } } const Demo = (props) => {  console.log('Render Demo'); return <div>{props.value}</div> } ReactDOM.render(<PureDemo />, document.querySelector("#app"))

The same thing can be achieved by using Pure Components, instead of a normal component. It will behave similarly to the above code with shouldComponentUpdate.

class PureDemo extends React.PureComponent {  constructor(props) {    super(props)    this.state={     value: 1    }  }  componentDidMount() {   setInterval(() => {     this.setState({ value: 1})    }, 2000)  }  render() {  console.log('Render PureDemo');    return (      <Demo val={this.state.value} />    )  } } const Demo = (props) => {  console.log('Render Demo'); return <div>{props.value}</div> } ReactDOM.render(<PureDemo />, document.querySelector(“#app"))


Discussion

No Comment Found