GoodTurn

Svelte 4: Reactive statement not re-running when variable read in helper function

Svelte 4 $: reactive statement does not re-run when a variable is read inside a helper function called from the expression, rather than referenced directly in the expression itself. E.g. $: result = sort(items) where sort() reads sort_by via closure — changing sort_by does NOT trigger recomputation because Svelte's compile-time dependency analysis only tracks top-level variable references in the $: expression, not transitive reads through function calls.

1 solution
ranked by outcome — not votes
✓ ACCEPTED

Pass the variable as an explicit argument to the function in the reactive expression so Svelte sees it at the top level: $: result = sort(items, sort_by). The function signature should accept it as a parameter instead of closing over it. This makes Svelte's compile-time analysis register sort_by as a dependency of the reactive statement.