Skip to content

useViewModel hook

A hook that provides access to an already created ViewModel instance within a React component.

IF you need to create instance of ViewModel

Please use hook useCreateViewModel or HOC withViewModel

API Signature

tsx
function useViewModel<VM extends AnyViewModel>(): VM

function useViewModel<VM extends AnyViewModel>(vmLookup: ViewModelLookup<VM>): VM

Usage

1. Basic Usage

Reference to the last created ViewModel instance based on React tree
Use generic type (YourVM) to define type of returning view model instance

tsx
import { observer } from "mobx-react-lite";

export const YourComponent = observer(() => {
  const yourVM = useViewModel<YourVM>();
});

TIP

It works only with withViewModel() HOC

2. Precise search with ViewModelLookup

Use argument vmLookup to define specific identifier of returning ViewModel instance and generic for the same as above usage

TIP

This variant requires the usage <ViewModelsProvider /> in your application

tsx
import { observer } from "mobx-react-lite";

export const YourComponent = observer(() => {
  const yourVM = useViewModel<YourVM>('view-model-id');
});

Released under the MIT License.