S
SolidJS8mo ago
Eugen

Does the createMemo() in the "Solid in 100 secs" vid make sense?

Hi - I just stumbled upon Solid, and the two introductory vids really made me curious, coming from React. I just wonder if the createMemo() usage in the video makes sense, assuming computation was really heavy. Because I would think that squared only gets recomputed when its dependencies - count in this case - change. Here's the code:
function Counter() {
const [count, setCount] = createSignal (10);
const squared = createMemo (() => count () ** 2);
return <p>{ squared() }</p>
}
function Counter() {
const [count, setCount] = createSignal (10);
const squared = createMemo (() => count () ** 2);
return <p>{ squared() }</p>
}
I can see though that it makes sense if there is an A - B - A change of count. In that case, the computation would not need to be redone in the case of the second A, when using createMemo.
3 Replies
peerreynders
peerreynders8mo ago
If a derived value has a fanout of one (only one, single dependant) then hypothetically the memo isn't improving things because the calculation will only be executed once anyway. if a derived value has a fanout of greater than one (more than one dependant) then each of those will cause it's own separate re-computation-which doesn't matter if it's relatively inexpensive. Wrapping an expensive derived value inside a memo means that the computation will only be run once regardless of how many dependants it has. In React you memo because you don't want to recompute on every render. That's not a problem in Solid as components only render once upon creation-after that updates go directly into the DOM via synchronous reactivity without re-rendering. The primary reason to memo in Solid is to ensure that the computation only runs once even when there are many other reactive values depending on that computation.
Eugen
EugenOP8mo ago
Awesome - Thanks for clearing this up! Btw will Solid's createMemo only cache the latest result, like React's useMemo does? If so, then the A - B - A case I mentioned at the end of my question would in fact not work the way I described it, but the second A would cause another re-evaluation.
peerreynders
peerreynders8mo ago
Correct
Want results from more Discord servers?
Add your server