Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Why are props not frozen?

React suggests not to mutate props. I was operating under the impression that when props are passed in, they would be immutable or frozen.

The code below does not throw any errors and mutates the prop. Is this a bug?

try{
  var a = this.props.a;
  a.push('one')
  a.push('two')
  a.push('three')
  console.log(a)
}catch(err){
  console.log(err)
}
like image 428
Anshul Koka Avatar asked Mar 14 '26 16:03

Anshul Koka


1 Answers

I'm not sure of the exact reasoning behind it or if that's documented somewhere but I could take a guess:

Freezing any assignment to a variable is not easy or even necessarily possible outside of using new-ish or even as of yet unimplemented browser features. Also deep freezing all your props in your app could have performance implications and would certainly need to be removed for prod builds.

Can you freeze assignment of a primitive variable? I don't think so. I think babel does it with const by statically checking code at compile time.

And can you freeze objects without Object.freeze or ES7's proxy? Again I don't think so, the es5-shim readme says:

which you cannot possibly obtain in legacy engines

What if someone does mutate something? These props are shallow copied, meaning you won't affect the parent prop unless you modify a nested object. However even if you did it would't affect the app, as that would get wiped out on the next render (just like your modifications).

If I got something wrong please let me know! This is just my reasoning.

like image 187
Dominic Avatar answered Mar 17 '26 09:03

Dominic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!