javascriptsveltesvelte-5

Effects no longer work with reactive objects when using runes


In Svelte 4, the effect below would fire every time user or pass props from it changed

let data = {
    user,
    pass,
};

$: data && clearErrors()

In Svelte 5 the equivalent code with runes would be:

let data = $state({
    user: '',
    pass: ''
})

$effect(() => data && clearErrors());

But now the effect does not run when user or pass props are changed. Can someone explain to me why this happens?


Solution

  • In Svelte 5 reactivity is fine-grained:
    If you reference just data, only a re-assignment of data itself will trigger the $effect.

    Either reference the properties individually, or if you really want to trigger on everything inside the object, use something like $state.snapshot to make sure all properties are evaluated.