What are Pure Components in React

What are Pure Components in React

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

Pure Components in React ProgrammingWhat 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

medium.com

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:

TechnoFunnel

Welcome to TechnoFunnel… This video is focussed on the concept of Promises in JavaScript. Async Await is the new?

www.youtube.com

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:

Master the JavaScript Interview: What is Functional Programming?

?Master the JavaScript Interview? is a series of posts designed to prepare candidates for common questions they are?

medium.com

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

Spread syntax

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more?

developer.mozilla.org

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.

Conclusion

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:

Introduction to React Hooks

How to use State Hooks in React

medium.com

React useEffect Hooks in Action

All you need to know about React?s useEffect Hooks

medium.com

?useContext? in React Hooks

Understanding React ?useContext? Hooks

medium.com

React?s Higher-Order Components (HOCs)

Understand React HOCs with the help of a use case

medium.com

The useMemo Hook in React

How to optimize performance with useMemo hooks

medium.com

15

No Responses

Write a response