What Are Pure Components in React
Posted By : Rajan Rawat | 30-May-2019
Introduction to Pure Components
Pure components were introduced in React 15.3. React
Here, I share my observations on how pure components can reduce unnecessary rendering.
import React from 'react';
class Car extends React.Component{
state={type:"Xylo"}
changeType = () => {
this.setState({ type:"Xylo"})
}
render(){
console.log("Car -- Render");
return (≤div≥Car
≤button onClick={this.changeType}≥Change Type≤/button≥
≤/div≥) }
}
export default Car
Here, render() will be called for each state set(), although we didn't represent the "type" attribute in JSX, nor did we change the "type" attribute. We need to stop calling render() in the first two cases. To do this, shouldComponentUpdate() must return true in the following way:
Only compare the attributes represented in JSX. Here, the "type" attribute is not represented in JSX. There is no need to re-render the Car component.
Check if the property is really changing, that is, is the "type" property really changing?
The pure component enters the scene in the second scene. The pure component compares all the properties of the current state with the next state, and the current attachment has the following support for each state call () or its primary state in the hierarchy. Therefore, it helps to reduce unnecessary calls to the render() method.
A very specific thing about pure components is a superficial comparison. JavaScript is completely
Conclusion
Pure components are great for classes with minimal and immutable properties. If we have to use them with nested objects with mutable objects, then maintaining invariance will be very complicated. I like to use Immutable.js in this case.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rajan Rawat
Rajan is a UI Developer, having good knowledge of HTML, CSS and javascript. His hobbies are internet surfing and watching sports.