Skip to content

ViewModel ​

A ViewModel keeps view-specific state, derived values, actions, and lifecycle work outside the UI component. With the appropriate framework integration, MobX tracks observable values read by the view and updates that view when they change.

Choose an implementation ​

  • Use ViewModelSimple for a small MobX class with optional lifecycle methods. It is the quickest choice for local component state.
  • Extend ViewModelBase when you need payload handling, mounting lifecycle hooks, access to a ViewModelStore, or the built-in unmountSignal.

Connect a ViewModel with the React integration or SolidJS integration. For a conceptual introduction to the pattern, see MVVM.

Example ​

The example assumes an application-provided getUserData helper that accepts a user ID getter and an AbortSignal.

ts
import { ViewModelBase } from 'mobx-view-model';

export class CurrentUserBadgeVM extends ViewModelBase<{ userId: string }> {
  private userData = getUserData(
    () => this.payload.userId,
    this.unmountSignal,
  );

  get badgeTitle() {
    return `User badge: ${this.userData.fullName || ''}`;
  }

  get isLoading() {
    return this.userData.isLoading;
  }
}