ReactJS Pure Components

Generally, In ReactJS, we use shouldComponentUpdate() Lifecycle method to customize the default behavior and implement it when the React component should re-render or update itself.

Prerequisite: 

 
 

Now, ReactJS has provided us a Pure Component. If we extend a class with Pure Component, there is no need for shouldComponentUpdate() Lifecycle Method. ReactJS Pure Component Class compares current state and props with new props and states to decide whether the React component should re-render itself or  Not.

In simple words, If the previous value of state or props and the new value of state or props is the same, the component will not re-render itself. Since Pure Components restricts the re-rendering when there is no use of re-rendering of the component. Pure Components are Class Components which extends React.PureComponent

Example:  Program to demonstrate the creation of Pure Components. 



javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

import React from ‘react’;
  
export default class Test extends React.PureComponent{
   render(){
      return <h1>Welcome to GeeksforGeeks</h1>;
   }
}

chevron_right


Output :

Extending React Class Components with Pure Components ensures the higher performance of the Component and ultimately makes your application faster, While in the case of Regular Component, it will always re-render either value of State and Props changes or not.

While using Pure Components, Things to be noted are that, In these components, the Value of State and Props are Shallow Compared (Shallow Comparison) and It also takes care of “shouldComponentUpdate” Lifecycle method implicitly.
So there is a possibility that if these State and Props Objects contain nested data structure then Pure Component’s implemented shouldComponentUpdate will return false and will not update the whole subtree of Children of this Class Component. So in Pure Component, the nested data structure doesn’t work properly.

In this case, State and Props Objects should be simple objects and Child Elements should also be Pure, means to return the same output for the same input values at any instance.

react-js-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.