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:
withViewModel()HOC - recommended wayuseCreateViewModel()hook - simplest way, more performant in many cases
2. Render in React tree
use withViewModel() HOC
Then you should render the component returned from this function
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
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:
- Create instance of
ViewModelStore - Wrap your application into
ViewModelsProviderContext Provider.
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.
