11

Why MobX encourage mutable objects in their docs??

But, I see a tutorial about MobX: http://orlandohamsho.com/javascript/mobx-react-tutorial-building-first-application/

And, he used immutable approach in his tutorial instead of mutable one (see below).

@action setUsers = (users) => { this.users = [...users]; (instead of pushing it)

I also think that immutablity approach is better (so that React.PureComponent can work which means optimizing performance)

Why MobX encourage to mutate object? What approach should I use?

Terry Djony
  • 1,584
  • 4
  • 18
  • 37

1 Answers1

10

it really depends on what you do. MobX doesn't use immutable concept, in fact, I don't think it's wise to immutable data in MobX. For example, if you add an item to an observable array, if you do it immutable way, the whole array will re-render. If you just simply push the item into the array, only the added item will render. There may be cases that you need to return a new array instead of mutating it, but in most cases, MobX should not use immutable way to update observable data.

XPX-Gloom
  • 561
  • 4
  • 11
  • Why would React re-render a component based only on 1 item in the array? Most of the time we map over arrays in the component, and the whole component is intended to be re-rendered. I don't see the practical point here. – Ilyas Assainov Feb 02 '21 at 13:18
  • If you have an array of 100 items to display, you change one item, you don't want to re-render all 100 items instead of just the updated one. That'll give you big performance improvement – XPX-Gloom Feb 08 '21 at 19:01
  • It seems react handle this issue with the "key" prop now. The all-rerender method only happend in prev versions of react – Caper Mar 12 '21 at 03:30