Reputation: 5674
After occupying myself a bit with learning React I still consider many of the concepts as hard to get.
Among other: The immutability of props.
If I get it right then components are, more or less, the equivalent to objects in object-oriented programming.
In object-oriented programming you pass data into objects via method-parameter. In React you got props for passing data into components.
If you pass a parameter to a Java-method then you can change these data within the method-body. No problem.
In React not possible because props are immutable.
All literature and stuff I've seen mentions these immutability as a important concept. But so far nobody have really told me why.
Can someone please tell me: What's the great benefit of having immutable props?
Or respectively: What would be the great disadvantage of not having immutability? What could happen if props are mutable instead?
Preferable as a good example. Then chances are bigger that I perhaps get it.
Upvotes: 5
Views: 541
Reputation: 4675
I'll keep it short as I am no expert in functional programming. I'm sure someone with far more experience will pitch in eventually.
Start off by thinking of your components, not in terms of Objects but instead, as functions (as in the mathematical term). Your component is a function of its properties. More specifically it's a render function. It takes props and returns HTML (actually it returns virtual dom trees, but that's irrelevant)
Functions in mathematics are pure. You give them an input, they give you an output. They do not have side effects and they do not use any other inputs. And that gives you some great benefits:
Those are just some benefits, an average developer like myself can see. I'm sure someone with real functional programming experience can come with tons more. Hope it helps
Upvotes: 8
Reputation: 242
The greatest benefit of immutability is that whatever your component renders is predictable. The resulting view is just a map of some props. Imagine if in a hierarchy each component are able to change the props that gets passed around. It will be hard to track whomever was the one who did the modification.
This is the reason why in functional programming pure functions and immutable types are the norm. It is easy to reason out -- a pure function is a pure mapping of input and output and that is it.
Upvotes: 3
Reputation: 31
(After reading the following Why can't I update props in react.js?)
It is a good separation of responsibilities if you can only change your own state, and you communicate your state indirectly with props. This results in a higher cohesion.
It is possible to make much less understandable code if you were allowed within component A to change state of component B by directly changing props.
I hope this answers the why.
Upvotes: 3