Skip to content

React MobX ​

Use @wirestate/react-mobx when React components should render MobX state held by services.

Observable state is defined with @wirestate/mobx, which re-exports MobX and provides decorator aliases such as Observable, Action, BoundAction, and Computed. React rendering is wired through @wirestate/react-mobx.

For MobX behavior and React integration details, use the official MobX docs and React integration docs.

Install ​

bash
npm install @wirestate/core @wirestate/mobx @wirestate/react @wirestate/react-mobx

Service ​

MobX decorators need makeObservable(this).

ts
import { Injectable } from "@wirestate/core";
import { Action, Observable, makeObservable } from "@wirestate/mobx";

@Injectable()
export class CounterService {
  @Observable()
  public count: number = 0;

  public constructor() {
    makeObservable(this);
  }

  @Action()
  public increment(): void {
    this.count += 1;
  }
}

Alternatively, register ObservablePlugin on the root container. It calls makeObservable for every activated service that carries MobX decorators, so services skip the constructor call.

ts
import { Container } from "@wirestate/core";
import { ObservablePlugin } from "@wirestate/mobx";

const container = new Container({ bindings: [CounterService], plugins: [new ObservablePlugin()] });

Component ​

Wrap components that read observable state with observer.

tsx
import { useInjection } from "@wirestate/react";
import { observer } from "@wirestate/react-mobx";
import { CounterService } from "./CounterService";

export const Counter = observer(function Counter() {
  const counter = useInjection(CounterService);

  return <button onClick={() => counter.increment()}>Count: {counter.count}</button>;
});

Computed Values ​

ts
import { Injectable } from "@wirestate/core";
import { Computed, Observable, makeObservable } from "@wirestate/mobx";

@Injectable()
export class CounterService {
  @Observable()
  public count: number = 10;

  public constructor() {
    makeObservable(this);
  }

  @Computed()
  public get isEven(): boolean {
    return this.count % 2 === 0;
  }
}

API Reference ​

Observable, Action, BoundAction, Computed, makeObservable, ObservablePlugin, observer.

See Also ​