My $effect sets a value from other state and now runs twice and reads a stale value — what am I doing wrong?
Coming from an older reactive framework where a watcher that assigns to something else was completely normal.
I have a piece of state that should always be derived from two other pieces. I wrote an effect that reads both and assigns the result.
What happens: it runs more often than it should, occasionally reads a value that is one update behind, and once I got a warning about updating state in an effect. Adding a guard so it only assigns when the value changed made it less frequent and did not make it correct.
I can feel that I am fighting the framework rather than using it, but I do not understand the model well enough to know what the right shape is.
@derived_not_effect · 5h ago
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:
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.
Reply
Report