MobX documentation suggests I should use observer
on all my components. However by using inject I get more fine grained control over what data causes a re-rendering of my components.
My understanding is I that with observer
, a change in all accessed observables in the last render will cause a re-render, even if the observable is nested deep in the data store, while inject
only re-renders when observables accessed in the injector function change.
For example:
class Store{
@observable data = {
nestedData: {
deepData: 'my_data'
}
}
}
const store = new Store();
... Assume the store is injected using <Provider /> component
// This will cause re-render when the data object changes
// for example: store.data = { new_data: 'new_data' }
@inject(stores => {
return { data: stores.dataStore.data };
})
class MyComponent extends Component { }
// This will re-render on change of the data object, but also
// on change of nestedData and deepData properties
@inject(stores => {
return { data: stores.dataStore.data };
})
@observer
class MyComponent extends Component { }
Could someone confirm my understanding of this?
In my opinion, it's better to use only inject
as it gives you more control, and can prevent unnecessary re-renders. If the data is deeply nested you could create a computed property that gets and prepares the data from the deep structure and then inject that property in the component.
Are there other benefits/drawbacks when using one over the other