mewi mewi - 4 months ago 8
Javascript Question

React: Why is it necessary to have immutable props if values are passed as by value anyway?

I not too deep into JavaScript. Therefore have done this tinkering:

var demo = 'test';

var obj = {
x: 'abc'
}

function foo(str) {
str += '_123';

return str;
}

var ret = foo(demo);
var retObj = foo(obj.x);

console.log('Result: %s', ret); // => 'test_123'
console.log('Used parameter: %s', demo); // 'test'

console.log('Result: %s', retObj); // 'abc_123'
// The value of the property is still unchanged. So
// it has been passed in as by value. As as copy.
console.log('Used parameter: %s', obj.x); // 'abc'


I pass a string to the function. One time as primitive variable and the next time as object property.

Afterward the original data are unchanged. => The outer system is unchanged.

Now I am wondering:

Why do they have these immutability feature in React?

I mean: They say a function shall do something and provide as result. But not changing the system as whole.

But if data are passed as by value anyway? Why do the make such a big thing out of having immutability?

Answer

In both examples you pass a string to the function. obj is an object, but obj.x is a string.

JavaScript treats strings and numbers (primitives) as immutable. So if you do:

var a = "bob";
var b = a;
b = "jack";

The original string a will be unchanged.

But objects are different. If you do:

var propsObj = { name: "bob" };
var newPropsObj = propsObj;
newPropsObj.name = "jack";

Then propsObj will also change, so propsObj is now { name: "jack" }.

React uses stuff you pass as props and state to make its virtual DOM. Because react uses these to see if anything changed, and render only stuff that did change, react relies on your code not to change props or state after you pass it to react.

In the second example, this will cause react to think that new and old props are still the same, so react will (incorrectly) conclude that it does not need to re-render.