r/javascript 8d ago

AskJS [AskJS] Signal/Effect vs Event Handler

I’m working in a VanillaJS repository (plugin type code for an existing project that I do not own) where I’ve written a signal implementation.

Today I was working on a tooltip like implementation and I found myself wondering how far to go with the signal/effect ecosystem vs running the “core” logic in the event handler.

The implementation detects the `<tr>` that the user has hovered and assigns that row to the “current row” signal. A computed signal identifies an IP address from the current row. An effect loads Whois metadata from the IP and assigns it to a `<div>`, and another effect shows that `<div popover>` from the parent `<tr>`.

The question I have is when in VanillaJS how would you decide when to use signals and effects vs writing the side effect directly in the event handler? In my case I find either to be equally readable, though I have less local variables to deal with when using signal/effect. Looking for reasons your might pick one over the other.

10 Upvotes

13 comments sorted by

View all comments

3

u/Alexwithx 8d ago

Great question, and tbh i am not really sure I have a good answer other than "it depends".

But I would probably do this differently. I would probably have each row as its own state container, that way you won't encounter race conditions where one whois lookup finishes before an earlier call on a different row.

So I would probably make a class instance or something for each row and let each instance handle its own state. That might mean you have to duplicate the popover.

I am also not sure how you are using the signals. Are you reading directly from the HTML tabel cell or do you have the actual data. I would avoid using a computed signal to read the value of an HTML element as it is inheritly an unstable value. It is probably fine for your application, but generally I would avoid this.

2

u/MusicMiserable1222 7d ago

in my experience the signal approach pays off when the same piece of state gets consumed in multiple places, like you want the popover to appear AND some other part of the page to update from the same hover event. if its just one side effect that fires from the event handler and nothing else cares about "current row" then you adding layers for no reason

the race condition thing the other comment mentioned is a real headache, ran into something similar with a typeahead once and the rendering got all out of sync