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
ViewModelSimplefor a small MobX class with optional lifecycle methods. It is the quickest choice for local component state. - Extend
ViewModelBasewhen you need payload handling, mounting lifecycle hooks, access to aViewModelStore, or the built-inunmountSignal.
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;
}
}