When is it a good idea to work with Pure Components?

Mayank Gupta
Jul 30 · 7 min read

React uses Pure Components to provide optimizations. In this article we will discuss scenarios in which using Pure Components is advantageous.


What are Pure Functions in JavaScript?

Pure Components do not depend or modify the state of variables outside their scope. These are the building blocks of Functional Programming. Before we get into the details of Pure Components in React, we need to understand the concept of Pure Functions in JavaScript.

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

Just like 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 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:

  1. “setState” is called in Component
  2. “props” values are updated
  3. this.forceUpdate() is called

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

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

Before we proceed further, we need to understand the concept of Shallow Comparison in JavaScript. The values saved in 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 as Reference type data. Comparing Primitive Values is not a concern, problems arise when we have reference values during 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 same, it results in “false” value. We can see the same in the code below.

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.

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.


Conclusion

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:

Better Programming

Advice for programmers.

Mayank Gupta

Written by

9 Years of Experience with Front-end Technologies and MEAN Stack. Working on all Major UI Frameworks like React, Angular and Vue.

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade