Replies: 1 comment 1 reply
-
This is a classic example of something that shouldn't have been an effect in the first place! Effects are about reacting to state being a certain way, not to state changing in a certain way. If you want to react to changes, use a callback (which could be applied as an event listener or a function binding or whatever). If you apply this mindset when thinking about how data flows through your app, you will free yourself of anxiety around when effects re-run. Effects running more or less frequently is a question of optimisation, not semantics. If we always added deduplication at prop boundaries, it would benefit this one specific case at the cost of others. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I keep running into the same issue with Svelte 5, and that's that my
$effect
s are running too often, when they depend on a component property. Let me show an example:In the parent component, we do something like this:
This code has a bug where it sends an email every second, not just when the email address changes. This happens despite
emailAddress
being the only dependency of the$effect
.Why? Because the parent component is rerendering
Child
every timestate
changes, and this triggers reactivity on all props in the child. To fix it, the child can wrap$derived
around each of its props (that are going to be used as a dependency of an$effect
):The
$derived
rune deduplicates reactions based on the reference equality of its computed result. Now the$effect
below stops reacting to an update ofprops
, and only still reacts to an update toemailAddress
, like we expect.To me, this feels very unintuitive, and it's annoying to have to write the extra boilerplate every time I want to create an
$effect
that reacts to a component property.I think it'd be much more intuitive if the same deduplication logic that happens at the boundaries of a
$derived
, also happen at the boundaries of individual component properties.What do you think?
Beta Was this translation helpful? Give feedback.
All reactions