Immutability and referential transparency in ReactJS

All ReactJS community talk about using the functional paradigm approach to code your ReactJS applications.
But… Why use this things? What are this things?
In this article we are going to talk about two parts of this functional programming approach: Immutability and referential transparency
According to the miles.no immutability is
An immutable object is an object whose state cannot be modified after it is created.
This is, don’t modify your objects, only create another with the new properties you want.
In Haskell wiki, referential transparency is described like this:
Referential transparency is an oft-touted property of (pure) functional languages, which makes it easier to reason about the behavior of programs
Like all functional languages, this property remember us math, in other words, what if we switch sqrt(9) by 3? nothing happens. which means that sqrt is a pure function, if you call sqrt 1 million times with the same parameters, the result still the same.
To all developers, sometimes, coding front end application is so much frustrating, you code anything and a thousand others are broken. That’s why we use things like this in ReactJS, functional programming have the idea to se things happen declaratively and with no side effects.
Long story short, Immutability make your state concise, if you code here, your data will be not reflected different way in other place, referential transparency, will make your functions highly reliable, let’s see this in code!
Let’s see immutability working on a Redux reducer
As you can see, there is no property ‘loading’ being edited by example, instead, we spread an object and overwrite property loading if exists, creating a new object.
With immutability you don’t have a wrong information, sometimes you’re just seeing a old version of your state.
I’ll not go deep in the fact of references and deeply equality in javascript, and how immutability helps the performance of reactive changes of react components, but the react docs itself tell to don’t mutate this.state directly.
Now, an example in code of referential transparency
In our example, canRenderFace is a pure function, the example of referential transparency, this is: no side effects
Why code in that way? There are many some pros:
- Writing tests come easily
- No side effects as already said
- Lean code and small functions
In other words, the functional approach is somethings that we have to resolve old problems, and write code more declaratively is the best way to have the control in your hands when maintaining your code base.
That’s all folks! I hope that i have contributed to clarify your mind!