Search code examples
statesveltewarningssvelte-5

Svelte warning - State referenced in its own scope will never update


I get this warning from Svelte

State referenced in its own scope will never update. Did you mean to reference it inside a closure?

but the code seems to work fine. Should I be worried about it?

this is the code with the warning:

const filteredOptions = $derived(pluck(["a", "b", "c"], allOptions))
let newFilteredOptions = $state(deepClone(filteredOptions));

let wasModified = $derived(!deepEqual(newFilteredOptions, filteredOptions))

allOptions is global state.

I am taking some props from it, put it in a derived state called filteredOptions and I am expecting allOptions to change its values after I press save, so I want this filter to always have latest values.

Then I create a state var called newFilteredOptions from a clone of filteredOptions which will be used in the bind:input fields.

Then I create another state var to check whether the newFilteredOptions objects differs from the current filteredOptions to determine if I should enable or disable the save button


Solution

  • The warning points out that your state newFilteredOptions will not update when the derived state filteredOptions is updated due to its dependencies changing. I.e. the value is only read once.

    See the warning documentation for examples.

    If you do not need newFilteredOptions updates after initialization, you can ignore the warning. Otherwise you may need an $effect to synchronize the state.