Before we can start looking into pure components, the concept of pure functions needs to be understood.

What is a pure function?

But what does this even mean????

A deterministic function is a function that when given an input, it always produces the same output. This means you can determine the result for example (x * 3) will always produce the same answer if n = 2 => 6.

Whereas a non-deterministic you can not predict the result. A non-deterministic function could be Math.Random(n), you can never sure what it will return. Some instance where functions will be non-deterministic is when the output relies on data like time.now, API’s within the function, or often when it relies on outside input, though this issue can be overcome.

Side effects

Side effects are when the code inside the function has a side effect outside the code. Some examples are console.log(), alert and changing outside variables. This will make more sense soon.

So what is the reason for pure functions?

So here is an example of changing a function into a pure function

This is not a pure function. First, the result of x = 4 will be different each time because the function relies on array which changes. Secondly, it has a side effect because it changes array.

This is how we change it to a pure function:

Because our function is creating a new array in the return it does alter the original array. This means it has no side effects. It also means that because array is not being altered

x=4 => [1, 2, 3, 4] no matter what.

Now we have a pure function.

What is a pure component?

Why do we need pure components?

But this so complicated, how does it work?

Some things to take into consideration

If you have a function inside the class and want the page to render each time the function is run, make sure the function is changing the state else it won’t re-render.

All the children of the pure component must also be pure.

If you want to do a deep comparison for pure components use the forceUpdate function, though this takes a lot of processing power.

So to make a pure component all you need to do is change

This

to this

and this

to this