Pure Components in React are the components which do not re-renders when the value of state and props has been updated with the same values. If the value of the previous state or props and the new state or props is the same, the component is not re-rendered. Pure Components restricts the re-rendering ensuring the higher performance of the Component
Features of React Pure Components
Prevents re-rendering of Component if props or state is the same
Takes care of “shouldComponentUpdate” implicitly
State and Props are Shallow Compared
Pure Components are more performant in certain cases
Similar to Pure Functions in JavaScript, a React component is considered a Pure Component if it renders the same output for the same state and props value. React provides the PureComponent base class for these class components. Class components that extend the React.PureComponent class are treated as pure components.
It is the same as Component except that Pure Components take care of shouldComponentUpdate by itself, it does the shallow comparison on the state and props data. If the previous state and props data is the same as the next props or state, the component is not Re-rendered.
Note: The State and Props are Shallow Compared
React Components re-renders in the following scenarios:
“setState” is called in Component
“props” values are updated
this.forceUpdate() is called
In the case of Pure Components, the React components do not re-render blindly without considering the updated values of React “props” and “state”. If updated values are the same as previous values, render is not triggered.
Pure Components restricts Re-Rendering
Take the scenario below, in which we’re updating the component’s state variable at a continuous interval of one second. With every call to “setState”, we update the counter value to the same value.
class ImpureComponent extends React.Component
{
constructor(){
super();
this.state={
counter: 0
}
// The value of Counter is updated to same value during
continues interval
setInterval(()=>{
this.setState({
counter: 0
});
},1000);
}
render(){
return<b>Counter Value: {this.state.counter}</b>
}
}
Here, setState is called and the value of “counter” is set to the same value. When setState is called, the component is re-rendered. In this scenario, the updated component view remains the same. There is effectively no difference in the UI — the new values are unchanged. Re-rendering, in this case, is an overhead.
In order to cater to this problem, React introduced Pure Components. They compare the initial and final values for the state and props variables. If there is no difference between the two, they won’t trigger the re-rendering logic for the component.
class ImpureComponent extends React.PureComponent{
constructor(){
super();
this.state={
counter: 0
}
// The value of Counter is updated to same value during
continues interval
setInterval(()=>{
this.setState({
counter: 0
});
},1000);
}
render(){
// This function wont be re-rendered in case when the new
state is same as previous
return <b>Counter Value: {this.state.counter}</b>
}
}
In the code above the component is inherited from React.PureComponent, each time the state or props are updated it compares the previous and next value — if the values are the same the Render function is not triggered. Performance is improved by not calling “render” recursively.
Shallow Comparison
Before we proceed further, we need to understand the concept of Shallow Comparison in JavaScript. The values saved in the variable can be either a primitive or reference type. Example “var a = 10”, here the value saved in the variable “a” is of primitive type. The data stored in Objects and Array can be referred to as Reference type data. Comparing Primitive Values is not a concern, problems arise when we have reference values during the comparison.
When we compare two different objects with the same properties, they equate to false. JavaScript looks for the object reference (Starting Address of the Object). Since the references are different, then even if the property values are the same, it results in “false” value. We can see the same in the code below.
var initialData={
name: "Mayank Gupta",
age: 30
}
var finalData={
name: "Mayank Gupta",
age: 30
}
// The value of "isEqual" equates to be "false" even if the property values are same
var isEqual=(finalData==initialData);
In the code below, we have two objects, userInfo and cloneData. We copy the value of userInfo in cloneData object. Both these variables are now pointing to the same object, since Objects are copied by reference. Updating any of the objects, update the other object as well, since they are referring to the same object. On comparison for equality, it returns true. So for any object, JavaScript look for the base address of the objects being referred.
var userInfo={
name: "Mayank Gupta",
age: 30,
designation: "Developer"
}
var cloneData=userInfo;
cloneData.name="Anshul Gupta";
if(cloneData==userInfo){
alert("Reference Comparison return true")
}
If we want to copy the object into a new object, we can use the spread operator.
To create a separate reference for the object, we can use the following lines of code:
var userInfo={
name: "Mayank Gupta",
age: 30,
designation: "Developer"
}
var cloneData={ ...userInfo};
if(cloneData==userInfo){
alert("Reference Comparison return true")
}
Pure Components Continued....
class ShalloWCompareComponent extends React.PureComponent{
constructor(){
super();
this.state={
userArray: [1,2,3,4,5]
}
// The value of Counter is updated to same value during
continues interval
setInterval(()=>{
this.setState({
userArray: userArray.push(6)
});
},1000);
}
render(){
return <b>Array Length is: {this.state.userArray.length}</b>
}
}
In the code above, before re-rendering, the initial and the final value of state and props object are compared with Shallow Comparison. Since we’re adding value to the same array object, the reference this.state.userArray remains the same. React Component will compare the reference of previous and the new state variable userArray. As they are point to the same reference, no change will be detected and the component will not be re-rendered, leading to the unexpected result in the user interface.
The key takeaway here is:
Use Pure Components, in the case when the props and state changes are made to primitive type variable, state and props changes to reference variable may lead to incorrect results and inconsistent rendering
Conclusion
Pure Components are introduced for performance enhancement. You can use this optimization to improve the performance of your components.
Source: Medium-Mayank Gupta
The Tech Platform
コメント