What are Pure Components in React

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

Mayank Gupta
Jul 30, 2019 · 8 min read
Pure Components in React Programming
Pure Components in React Programming
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.


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.

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

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:

  1. “setState” is called in Component
  2. “props” values are updated
  3. 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

React Pure Components for Performance Optimization
React Pure Components for Performance Optimization
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

Image for post
Image for post
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 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.

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


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.


TechnoFunnel

TechnoFunnel focus on learning and understanding the programming concepts

Sign up for TechnoFunnel

By TechnoFunnel

Getting stared with Latest Technologies. Connect with us for more detailed articles and in-depth explanation of many frontend and backend Technologies and concepts Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

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 https://medium.com/technofunnel

TechnoFunnel

We are focussed towards learning different technologies like React, Angular, Machine Learning, Python, Golang and AWS. Follow us for detailed conceptual understanding of these technologies and Interview Preparations.

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 https://medium.com/technofunnel

TechnoFunnel

We are focussed towards learning different technologies like React, Angular, Machine Learning, Python, Golang and AWS. Follow us for detailed conceptual understanding of these technologies and Interview Preparations.

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store