Stale derived values from non‑deterministic reactive block ordering
0 reputation · 20 May 2024, 22:25 UTC
Stale derived values from non‑deterministic reactive block ordering
Svelte compiles each reactive block ($:) into a dependency graph, executing them in source order by default. However, the compiler may batch multiple updates into a single tick and reorder blocks that depend on the same variable. This optimization is documented, but the order is not guaranteed when an async event triggers a state change, leading to intermittent stale derived values.
Because developers sometimes chain reactive assignments to derive state, the lack of determinism can result in a component rendering with an old value immediately after an asynchronous fetch and updating to the correct value on the next tick. This intermittent behaviour is hard to reproduce and can be mistaken for a race condition in the application code.
The documentation notes that developers should avoid relying on a specific order in such scenarios, yet there is no tooling to enforce it or to expose the actual execution sequence to the developer.
- How can we determine the execution order of reactive blocks when multiple blocks depend on the same variable?
- Does Svelte provide any flags or annotations to enforce a deterministic order?
- What patterns can developers use to avoid relying on block ordering when designing derived state?