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.Component and React.PureComponent differ in the implementation of the shouldComponentUpdate() lifecycle method. The shouldComponentUpdate() method determines the re-rendering of the component by returning a boolean. In React.Component, it returns true by default. But in a pure component, shouldComponentUpdate() will compare the state for any changes, or whether to re-render the component.

 

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 object based. The comparison is based on an address reference. In surface comparisons, object references are compared, leaving internal references in the object without comparison. This creates problems when dealing with objects with variable nesting structures as well as pure components.

 

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.

About Author

Author Image
Rajan Rawat

Rajan is a UI Developer, having good knowledge of HTML, CSS and javascript. His hobbies are internet surfing and watching sports.

Request for Proposal

Name is required

Comment is required

Sending message..