In my React code, I am using and calling computedFn in multiple places. However, when I do console.log or debug step by step, I don't see it's memorizing anything, instead, it would execute the logic inside computedFn every time I call it.
Here is the code example in a .ts file:
const getComp = computedFn((num: number) => {
console.log('**** get computed num');
return num * num;
});
function testComputedFn() {
for (let i = 0; i < 10; i++) {
getComp(8);
}
}
And I can see that '**** get computed num' 10 times in console. So it seems like the memorization is not working at all? Not sure if I missed anything?
Here is a similar code where it can be test: https://playcode.io/1447230
Mobx computed
's only memoize stuff inside reactive context, e.g. inside of observer
, reaction
and etc. Otherwise computed expressions are evaluated each time their value is requested, so they behave just like a normal property/method (no caching).
So to fix your example you just need to wrap App
component with observer
HOC.
import { observer } from 'mobx-react'
export const App = observer(...)