When is it a good idea to work with React Pure Components?
What is React Pure Components
Technofunnel brings another article on how React uses Pure Components to provide optimizations. In this article, we will discuss scenarios in which using Pure Components is advantageous. We also discuss the difference between React Component and React Pure Components. The article demonstrates the scenarios when React Pure Components should be used and when it should not be used.
You can also look for the following article for more optimization techniques.
22 Performance Optimization Techniques for React
Simple and effective optimization steps for better React app performance
You can join us on our YouTube channel:
For a video tutorial on the benefits of Pure Component, refer to the following
These are the key features of Pure Functions:
1. Pure functions are deterministic
The definition of Pure Component says that for specific input parameters, we always have a specific output. The output is solely dependent on Input parameters and no other external variable.
Here is a simple example of Impure Function:
The above function takes an input parameter ?newValue? and adds value from an external variable ?initialValue? to it. In this case, the function is dependent on variables that are not in the scope of this function, so they introduce Impurity to the given function.
The code specified above is another example of the impure function, where the function is modifying the global variable getInitialValue, which does not lie under the scope of this function. Modifying this variable results in the introduction of Impurity to the function, making it Impure.
Now, let?s look for the simple Pure Function:
The function given above defines the output on the basis of the input parameter only. No variable, other than the input parameter, is adding its impact to the output. Also, we can see that the function does not modify any other variable that does not belong to this function. Hence it adheres to the concept of Pure Functions.
Browser optimizations via Pure Functions
Pure Functions have a huge performance impact during execution on the Browser.
Picture a scenario where a specific Pure Function is getting called multiple times. The Application calls for the same function multiple times with the same parameters ? assume ?add(10, 20)?. After executing it multiple times, the Chrome V8 Engine tries to optimize the code further by storing the execution result of the following function call. On the next call to the same function, with the same parameter, instead of executing the function again, the cached result is returned. Hence enhancing the Application Performance.
2. Functions should not introduce side effects
If the application updates certain data that is observable outside the called function, it can be considered a side effect introduced by the function. Here are a few scenarios:
- Modifying any external variable or object property
- Logging data to the console
- Writing Data to a file
- Writing data to the network
- Triggering any external process
- Calling any other functions with side-effects
- Making Asynchronous Data Calls
We need to avoid these side effects inside Pure Components.
Refer to this article for further details:
For now, we will focus back on Pure components in React.
Pure Components in React
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
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
Photo by Nadine Shaabana on Unsplash
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.
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.
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.
Props and State Changes are Shallow Compared
Photo by Dawid Zawi?a on Unsplash
In case of React Pure Component, the changes in react ?props? and ?state? is Shallow Compared. We need to understand the concept of Shallow Comparison before we proceed.
Understanding Shallow Comparison
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:
For more details on spread operators, see following here:
Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more?
Let?s Continue With Pure Components?
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
How Can We Resolve the Shallow Comparison Problem?
The simple answer is to work with immutable data.
In the example above, we can see that comparing reference variables can lead to a problem ? only the address of the object are compared before and after the update. Since we?re comparing references, the address still remains the same and the Pure Component does not detect any changes and does not re-render. We can resolve this by creating a new instance of the state variable if it represents the reference type.
Let?s see below, how we can resolve this issue:
In the code above, we?re creating a new reference array using the spread operator. When the setState is called, the component looks for the reference of a previous array object and a new array object is created. The reference is different since this is a new instance of the array, so the object has a new address. Now the pure component will get to know that the data has been updated, the ?render? life cycle will be invoked and the component will be re-rendered with correct values.
Pure Components are introduced for performance enhancement. You can use this optimization to improve the performance of your components.
You can look for more React article from the same author: