In MobX, @observable and @observable.ref are two decorators used to define observable states. The main difference lies in how they respond to data changes.
@observable
The @observable decorator makes a property observable. When applied to object properties, MobX performs deep observation on the object's properties. This means that if the property value is an object or array, changes within it will also trigger observers. In short, @observable enables deep observation.
Example:
javascriptimport { observable } from 'mobx'; class Store { @observable person = { name: 'John', age: 30 }; } const store = new Store(); autorun(() => { console.log(store.person.name); // When person.name changes, this re-runs }); store.person.name = 'Jane'; // Triggers autorun
@observable.ref
Unlike @observable, @observable.ref does not perform deep observation on objects or arrays; it only tracks changes in the reference of the property. That is, observers are triggered only when the entire object or array reference changes. This is beneficial for performance optimization, especially when dealing with large objects or arrays where you only care about reference changes rather than content changes.
Example:
javascriptimport { observable } from 'mobx'; class Store { @observable.ref person = { name: 'John', age: 30 }; } const store = new Store(); autorun(() => { console.log(store.person.name); // Runs initially }); store.person = { name: 'Jane', age: 30 }; // Triggers autorun, as the person reference changed store.person.name = 'Doe'; // Does not trigger autorun, as it's only an internal property change
Summary
Choosing between @observable and @observable.ref depends on your specific needs:
- Use @observable if you need to observe changes within an object.
- Use @observable.ref if you only need to track changes in the reference of an object or array, which is typically used for performance optimization.