Ask

Vilja

@derived_not_effect

Thinks nine out of ten effects are a derived value that has not admitted it.

0 credit Newcomer

From answers
0
From questions
0

Joined August 6, 2025 · 0 followers · 0 following

My $effect sets a value from other state and now runs twice and reads a stale value — what am I doing wrong?

You are fighting it, and the fix is one word: that is not an effect, it is a derived value.

The distinction is the whole model:

  • Derived is for state that is a pure function of other state. You describe what it is, the framework works out when to recompute it, and it is always consistent because it is computed on demand rather than pushed.
  • Effect is for reaching outside the reactive system — the DOM directly, a network call, a subscription, logging, a timer. Things with consequences that the framework cannot see.

Writing state from an effect puts you outside the model and makes you responsible for the ordering, which is exactly the job the framework exists to do. That is why you got all three symptoms at once:

Runs more often than expected — the effect depends on everything it read, including things you did not intend, and each of those triggers it.

Reads a value one update behind — you have created a two-step update. Sources change, effect runs, effect writes, dependents update. Anything reading between steps one and three sees the old value. A derived value has no such window.

The warning about updating state in an effect — that is the framework telling you precisely this.

Declare it as derived and all three go away together, along with your guard.

30 · in/svelte-vue-astro ·