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
If you are using 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 {}
const YourComponentView = observer(({ model }: ViewModelProps<YourComponentVM>) => {
return (
<div>
{model.id}
</div>
)
})
const YourComponent = withViewModel(YourComponent)(YourComponentView)
const YourApp = () => {
return (
<YourComponent />
)
}
wrapping into observer
HOC is optional if you are not using MobX observables
If you are using 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] Using 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
ViewModelsProvider
Context 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.