1

Every time in react I care about immutable array operations to avoid accidental state changes via mutable operations

I often use immutable operations

whenever I need to add a new item I use this

[...myArr, 'newItem'];

instead of mutable oprations

myArr.push('newItem');

However, I saw an example of mobx on the official doc, And I was surprised because they use push() method.

I am a beginner in mobx, and I am afraid to use mutable operation,
Does anyone have an idea about it?

am I doing wrong or Can I go with a mutable operation on mobx with react?

Hidayt Rahman
  • 2,490
  • 26
  • 32

2 Answers2

1

This operations have different semantics and consequences, everything depends on what your goal is.

Do you need to notify all observables that this array changed? Then create new array, like that [...myArr, 'newItem']; or any other way you prefer.

Do you just need to add an item to array? Use push

For example, every useEffect that has deps for that array will react in the first case, but there will be no effect in the second case when you push:

useEffect(() => {
  // ...
}, [myArray])
Danila
  • 15,606
  • 2
  • 35
  • 67
  • You mean I can use anyone depends on the situation? but trust me I saw many posts of `react` where they restrict to use of these mutable methods `push()` `splice()` – Hidayt Rahman Jun 27 '21 at 04:56
  • 1
    Yes, you can use both with MobX. React actually does not have observers and reactive data so if you use pure React state it might be better to stick with immutable approach. – Danila Jun 27 '21 at 10:44
  • Thanks, You saved my brain to be messed :) – Hidayt Rahman Jun 30 '21 at 08:02
  • @HidaytRahman please mark some answer as accepted if your question was resolved, thank you – Danila Jul 02 '21 at 12:23
0

Spread operator with ... create a new array, that needs to allocate some memory. So, it kind of costly in comparison to push

let arr = [1, 2, 3];
let arr2 = [...arr]; // like arr.slice()

arr2.push(4);
//  arr2 becomes [1, 2, 3, 4]
//  arr remains unaffected

Read more here

Abhinav Kumar
  • 2,883
  • 1
  • 17
  • 30