ReactJS and immutability

I have been studying ReactJS for a while. One of the things that puzzles me is why ReactJS uses immutability in many aspects, such as props, elements, etc. Is there any specific reason for this? What is the philosophy of this?

When I try to add a new property in props , I get the following error.

Uncaught TypeError: cannot add me property, object does not expand

+5
source share
2 answers

React uses immutability for obvious performance reasons. for instance

The idea is when you set the state, you do not mutate the state, but clone part of it, and then update the state

for instance

 this.state = { entries: [1,2,3] } 

you have to do

 this.state.setState({ entries: this.state.entries.slice().push(9); //not this.state.entries.push(9) }) 

Performance gains are achieved when you use shouldComponentUpdate

in shouldComponentUpdate you can just compare the links and not do a deep check

 shouldComponentUpdate(prevState,newState){ return prevState.entries != newState.entries } 
+3
source

The philosophy behind this is a one-way data stream — data streams (from the top level to the sheet components) and actions flow.

The component receives its data from the props and changes something, it must call its parent and ask him to change something - usually using the callback function.

You can read more about this on the Thinking in React page of the official website, this explains the concept very well.

+5
source

All Articles