Ernesto
Ernesto

Reputation: 944

Javascript pass by reference and props in react

As I understand correctly in Javascript we have two different passing: by value and by reference. By value is when we pass the strings or numbers. By reference when we pass the objects or arrays.

Last time in some project I noticed antipattern -> someone assigned new value to this.props.arrayOfNames = newArrayOfNames;

I haven't had the chance to test it, but... will it change somehow the parent's object? By reference?

Upvotes: 0

Views: 271

Answers (1)

Estus Flask
Estus Flask

Reputation: 222369

this.props.arrayOfNames = newArrayOfNames is not an antipattern but a mistake. props object is immutable, this is ensured by the use of Object.freeze in development mode. The assignment of arrayOfNames property value will result in error.

If props should differ from received ones, a correct way is to use a state that derives from props with getDerivedStateFromProps hook.

Upvotes: 5

Related Questions