PureComponent

Advertisement

PureComponent do the shallow comparision and re-render the Component.

E.g. If our states is not change and we try to re-render the component then it check there is now

We can use the PureComponent to improve performance.

  • In¬†below¬†example¬†we¬†have¬†created¬†`Welcome`¬†and¬†extend¬†it¬†with¬†`PureComponent`.
  • Initilize¬†the¬†`count`¬†state¬†with¬†`0`.
  • On¬†`componentDidMount()`¬†set¬†the¬†`1000¬†ms`¬†/¬†`1¬†second`¬†interval¬†with¬†`setInterval()`.
  • And¬†for¬†each¬†second¬†we¬†set¬†the¬†same¬†value¬†`0`¬†to¬†our¬†`count`¬†state.
  • Also¬†for¬†testing¬†used¬†`componentDidUpdate()`¬†life¬†cycle¬†method¬†which¬†trigger¬†after¬†updating¬†the¬†component.
  • In¬†Console¬†log¬†we¬†see¬†the¬†`componentDidUpdate`¬†log¬†only¬†once.
  • Becase¬†when¬†the¬†state¬†change¬†after¬†1¬†second¬†then¬†PureComponent¬†check¬†that¬†there¬†is¬†no¬†diff.¬†from¬†old¬†and¬†new¬†state¬†value.
  • So,¬†PureComponent¬†avoid¬†the¬†re-render.
  • Instead¬†of¬†`PureComponent`¬†if¬†we¬†use¬†`Component`¬†then¬†for¬†each¬†second¬†we¬†see¬†the¬†log¬†`componentDidUpdate`¬†in¬†console.
import React, { PureComponent } from 'react';

class Welcome extends PureComponent {
	constructor() {
		super();

		this.state = { count: 0 };
	}

	componentDidUpdate() {
		console.log( 'componentDidUpdate' );
	}

	componentDidMount() {
		setInterval( () => {
			this.setState({
				count: 0
			});
		}, 1000);
	}

	render() {
		return <h1>Count: { this.state.count }</h1>
	}
}

function App() {
	return <Welcome />
}

export default App;
%d bloggers like this: