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?
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])