DEV Community

loading...

Discussion on: Building a Reactive Library from Scratch

Collapse
bluebill1049 profile image
Bill • Edited

Hey Ryan,

Thanks for the blog post.
Q: What's the difference between

const displayName = createMemo(() => {
  if (!showFullName()) return firstName();
  return `${firstName()} ${lastName()}`;
});
Enter fullscreen mode Exit fullscreen mode

vs

const displayName = () => {
  if (!showFullName()) return firstName();
  return `${firstName()} ${lastName()}`;
};
Enter fullscreen mode Exit fullscreen mode

createEffect(() => log("My name is", displayName()));

and without the createMemo, for my understanding, the subscription will be the same outcome, right?

Cheers
Bill

Collapse
ryansolid profile image
Ryan Carniato Author

You are correct. Good on you for noticing. I often have to teach people where they can use less primitives. People new to reactivity tend to overuse them, and it probably doesn't help that intro examples tend to be overly simplistic to illustrate mechanics rather than practical. And here I am guilty of that here.

In this scenario where there is only a single observer that has no other dependencies this will effectively execute the same number of times. I explain this and the example a bit more in my previous article A Hands-on Introduction to Fine-Grained Reactivity. I show an example in that article illustrating the difference between using a thunk or using createMemo in an example where it does make a difference.

The main benefit of createMemo is to prevent re-calculations, especially expensive ones. This is only relevant if it is used in multiple places or the thing that listens to it could be triggered a different way which could also cause re-evaluation. It's just a caching mechanism, and like any memoization premature application actually can have negative impact since it costs extra memory and brings creation overhead. In real apps in any example where I was just calculating a string I'd probably not bother and just function wrap if there was reason not to inline it. But I'm also a bit of a performance nut.

Aside: This is actually one of the reasons I personally like explicit reactivity. A lot of libraries/APIs sort of push this memoization on you by default or hide it in their templating. It's excellent for update performance but you end up with higher creation costs. A typical sign of this behavior is when they have APIs like isObservable etc.. as it means they make decisions based on a value being a primitive so wrapping in a thunk would not be sufficient.

Collapse
bluebill1049 profile image
Bill

Thanks for the awesome and detailed reply. It does make sense. I really enjoy those reactive programming articles, hope to see more in the near future. ✌🏻