VJAI
VJAI

Reputation: 32758

ReactJS and immutability

I've learning ReactJS for a while now. One of the thing that puzzles me is why ReactJS uses immutability in many aspects like props, elements etc. Is there any specific reason for this? What is the philosophy behind this?

When I try to add new property to props I'm getting the below error.

Uncaught TypeError: Can't add property me, object is not extensible

Upvotes: 5

Views: 261

Answers (2)

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

React uses immutability for obvious performance reasons. For example

Idea is whenever you are setting a state , you dont mutate a state but you clone a part of it and then update the state

For example

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

you should 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 references and not due deep checking

shouldComponentUpdate(prevState,newState){
  return prevState.entries != newState.entries

}

Upvotes: 3

Gosha A
Gosha A

Reputation: 4570

The philosophy behind this is one way data flow — data flows down (from top level to leaf components) and actions flow up.

A component receives its data from props, and to change something, it has to call into its parent and ask it to change something — via a callback function usually.

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

Upvotes: 5

Related Questions