Why to observe?

MobX is based on concept of observables which may feel like magical tiny boxes (as everything unknown), but it's fairly simple actually.

If you have ever worked with PubSub-like patterns (eg. EventEmitter), the observable it's fairly similar concept, but wrapped into a fancy package.

✨ It will manage subscriptions automatically while you focus on declaring what data you need.

⏱ It's time-proof. You will always get a latest value no matter when you start observing.

This is very useful in the React world as you can stick to a declarative way of writing components and simply work with data without additional hurdles and boilerplate.

  1. function LogoutWidget() {
  2. const { user } = useStore()
  3. return useObserver(() => (
  4. <Link to="/logout">
  5. <span className="name">{user.name}</span>
  6. </Link>
  7. ))
  8. }

With the usual React paradigms (e.g. useReducer) such a component cannot re-render itself based on a change of user.name. The parent component needs to cause an update to the child component, and that's not very efficient.

With observer in place, the component itself can be notified about the change (as long as user is observable) and do a re-render without a parent ever knowing about it.

Continue reading on how to make your components reactive.