Skip to content

Integration with React

Integration consists of 2-3 steps.

1. Connect ViewModel with View

Your ViewModel should be connected to a React view component.
To achieve this you can use:

2. Render in React tree

use withViewModel() HOC

Then you should render the component returned from this function

tsx
import { ViewModelBase, ViewModelProps } from "mobx-view-model";
import { observer } from "mobx-react-lite";

class YourComponentVM extends ViewModelBase {}

export interface YourComponentProps extends ViewModelProps<YourComponentVM> {
  yourProp?: string;
}

const YourComponent = withViewModel(
  YourComponentVM,
  ({ model, yourProp }: YourComponentProps) => {
    return <div>{model.id}</div>;
  },
);

const YourApp = () => {
  return (
    <YourComponent />
  )
}

use useCreateViewModel() hook

Then you should render your React components using this hook

tsx
import { ViewModelBase, useCreateViewModel } from "mobx-view-model";
import { observer } from "mobx-react-lite";

class YourComponentVM extends ViewModelBase {}

const YourComponent = observer(() => {
  const model = useCreateViewModel(YourComponentVM);

  return (
    <div>
      {model.id}
    </div>
  )
})

const YourApp = () => {
  return (
    <YourComponent />
  )
}

3. [Optional] Use ViewModelStore

ViewModelStore is a powerful tool that allows you to look up and access your view model instances anywhere.
To use this store:

  1. Create instance of ViewModelStore
  2. Wrap your application into ViewModelsProvider Context Provider.
tsx
import { ViewModelsProvider, ViewModelStoreBase } from "mobx-view-model";

const vmStore = new ViewModelStoreBase();

const YourApp = () => {
  return (
    <ViewModelsProvider value={vmStore}>
      ...
    </ViewModelsProvider>
  )
}

With this step you can use the useViewModel() hook with the first argument

isMounted state

This state is based on calling the mount() method, which is triggered inside the useCreateViewModel() hook or the store lifecycle.
Because of this, on the first render isMounted will be false, since mounting happens inside a useLayoutEffect/useEffect hook.

Do not calls mount(), unmount() manually

This methods already calling inside ViewModelStore base implementation or inside useCreateViewModel hook.

Released under the MIT License.