These are the key features of Pure Functions:
1. Pure functions are deterministic
Thee 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 a input parameter “newValue” and adds value from an external variable “initialValue” to it. In this case the function is dependent on variables which are not in 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 global variable
getInitialValue, which does not lie under the scope of this function. Modifying this variable results in 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 do 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 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 which 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 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
PureComponent base class for these class components. Class components that extend the
React.PureComponent class are treated as pure components.
It is 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 same as next props or state, 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
In 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 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.
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
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 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:
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 of
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 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 anew 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 spread operator. When the
setState is called, component looks for the reference of previous array object and new array object is created. The reference is different since this is a new instance of 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 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.
For More Optimization Techniques, follow the Article: