My learning about Pure Components in React.js

What is a pure function?

Pure functions only perform a calculation and nothing more.

A pure function follows these rules:

  1. It never changes any variable or object that existed before the function was called.

    For eg.

let variableDeclared = 0;

const functionToCall = () =>{

variableDeclared = variableDeclared + 1

return variableDeclared

}
  1. Given the same input to the function, it should return the same result always.
 function add2(input)
  { return input+2} 
  // this should always return 4,
  // if we provide the value of input as 2

React expects every component we write should be a pure function. That means every react component we write should always return the same JSX for the same inputs. It should not change any objects or variables that existed before rendering.

Here is an example of an impure component:

Here is what I got when I tried to see the output:

This component is reading and writing a counter variable declared outside of it. So, calling this component will generate different JSX. If any other component tries to read the value of the counter, they will read some other value depending on when they were rendered. This is happening because, the component is trying to change the value of a preexisting variable during rendering, also known as mutation.

Here is an example of a pure component:

Here is what I got when I tried to see the output

So, the output is always the same no matter where we are trying to read it from.

It is producing the same JSX for the same given input and also it is not modifying any variable or object declared before it renders. So, it fulfills the criteria of being a Pure Component.

This is the gist. There are many more things written in detail. You can go through the react.dev link for better clarity.

https://react.dev/learn/keeping-components-pure

Here is the code sandbox link.

https://codesandbox.io/s/async-thunder-2xgrf6?file=/src/App.js