3

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?

mewi
  • 539
  • 1
  • 4
  • 11
  • 1
    If you passed the actual object to the function then the function could mutate that object (including changing or deleting its existing properties and adding new ones). – nnnnnn Jul 31 '16 at 07:05
  • Not everything is passed by value. – Mulan Jul 31 '16 at 07:58
  • Possible duplicate of [Why are React props immutable?](https://stackoverflow.com/questions/47471131/why-are-react-props-immutable) – dǝɥɔS ʇoıןןƎ Jun 18 '19 at 16:07

1 Answers1

3

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.

wintvelt
  • 13,855
  • 3
  • 38
  • 43