I noticed that useLocalObservable
makes functions into mobx actions
automatically, the same way that makeAutoObservable
does for classes.
Does it also make getters into mobx computed
values?
import { useLocalObservable } from 'mobx-react-lite';
const state = useLocalObservable(() => ({
isShowDragMeTooltip: false,
showDragMeTooltip() {
this.isShowDragMeTooltip = true;
},
hideDragMeTooltip() {
this.isShowDragMeTooltip = false;
},
get dragMeTooltipStyles() {
return {
display: this.isShowDragMeTooltip ? 'block' : 'none',
};
}
}));
In the code above, is dragMeTooltipStyles
a computed value with its own memoization, or will it be a normal getter that is recalculated every time it is called?
Yes, it makes the getter a computed
value, it will be memoized and etc.
But don't forget that it will only be memoized in the observable context, e.g. if you call it in the React render function of observer component, for example.
If you call it from the useEffect
or something like that, which is not in the observable context, it will be recalculated for every call.
I've made a quick example to demonstrate how it works for different contexts: