Search code examples
reactjsimmutabilitymutablemobxmobx-react

MobX Mutability vs Immutability


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?


Solution

  • 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.