Pure Components

In this article, we will discuss what are pure functions in javascript? What are pure components? When to use pure components in React and when not to use them? What is the difference between Pure components and class and functional components? What are the advantages of pure components over others?

When a function is called a pure function in javascript?

A function is called pure function if the following criteria are met:

  1. The function should not produce any side effects, for example, making a network call, making a call to another function that has side effects, mutation data, etc.
  2. The function should be dependent only on the input parameters.

What are pure components?

Pure components in React are the component that did not re-render when the value of state and props has been updated with the same values.

A Pure component implements the “shouldComponentUpdate” lifecycle method by performing a shallow comparison on the props and state of the component. Now, what is shallow comparison?

Primitive types

A (shallow comparison) b returns true if a and b have the same value and are of the same type.

Example string “ravi” (shallow comparison) “ravi ” returns true.

Complex types

 A (shallow comparison) b returns true if a and b reference exactly the same object.

var a =[1,2,3];

var b =[1,2,3];

var c=a;




var ab_eq = (a===b); //false

var ab_eq = (a===b); //true




var a =[ x : 1, y : 2 ];

var b =[ x : 1, y : 2 ];

var c=a;




var ab_eq = (a===b); //false

var ab_eq = (a===b); //true

The pure component uses shallow comparison for checking the current value with the previous state.

Shallow comparison of the previous state with the current state.

(difference)  component will  re-render

Shallow comparison of previous value with the current value.

How can we create a pure component?

We can create a component by extending the pure component class.

Difference between Regular component and Pure component.

Regular component

Pure component

A regular component does not implement the

 “shouldComponentUpdate” method.

It always returns true by default.

A Pure component implements the “shouldComponentUpdate” lifecycle method by performing a shallow comparison on the props and state of the component.

Advantages of using Pure components

  1. If there is no shallow comparison difference then the component will not re-render and performance will get boosted.
  2. It is a good idea to ensure that all the children’s components are also pure to avoid unexpected behavior.
  3. It takes care of the “shouldComponentUpdate” method implicitly.

 

Leave a Reply