Integration with React
Integration consist of 2-3 steps.
1. Connect ViewModel with View
Your ViewModel should be connected with React view component
To achieve this you can use:
withViewModel()HOC - recommended wayuseCreateViewModel()hook - simplest way, more performant
2. Render in React tree
use withViewModel() HOC
Then you should render 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(
YourComponent,
({ model, yourProp }: YourComponentProps) => {
return <div>{model.id}</div>;
},
);
const YourApp = () => {
return (
<YourComponent />
)
}use useCreateViewModel() hook
Then you should render your React components with using this hook
import { ViewModelBase, ViewModelProps, 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 very powerful thing which allows you to lookup and get access to your view model instances everywhere.
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 useViewModel() hook with first argument
isMounted state
This statement totally based on call mount() method which calls inside useCreateViewModel() hook.
Because of this on the first render isMounted will be false, because mounting happens inside useLayoutEffect\useEffect react hook.
Do not calls mount(), unmount() manually
This methods already calling inside ViewModelStore base implementation or inside useCreateViewModel hook.
