svelte icon indicating copy to clipboard operation
svelte copied to clipboard

Unexpected "State referenced in its own scope will never update" warning

Open geoffrich opened this issue 1 year ago • 1 comments

Describe the bug

When initializing the tweened store with a derived value, I get a warning: "State referenced in its own scope will never update. Did you mean to reference it inside a closure?"

Seems like a false positive to me, though I could be missing something. I want to initialize the tweened store to the initial value of the derived expression. I could duplicate the logic, but would rather avoid if possible.

Expected behavior: no warning is shown

<script>
	import { tweened } from 'svelte/motion';
	let count = $state(1);
	let doubled = $derived(count * 2);
	let tweenedDouble = tweened(doubled);

	$effect(() => {
		tweenedDouble.set(doubled);
	})

	function increment() {
		count += 1;
	}
</script>

<p>{$tweenedDouble.toFixed(2)}</p>
<button onclick={increment}>
	clicks: {count}
</button>

Reproduction

https://svelte-5-preview.vercel.app/#H4sIAAAAAAAAE1WR0WrDMAxFf0WYQJNtLLSPWRIYjP3EsofWVsA0sY0tdxvG_z4nDi15lHTuvUIKbJQTOtZ8BabOM7KGvRvDXhj9maVwN5wIU-20t3zptI5baagf1EByNtoSBKAfRIUCIoxWz3DIsnrWJLU6vC3shARce0XQQeHoTFgeq_tEaH-ZkkGaCbTyhqLM8BOcHtQW87HCid3qclOvYEILHEfkVJYVdD2EpTXQTvvqkHYqilXWjl7xZWmQilucUVFy2SzyRs8dHLNkUG39uIZqTR-KfQzpT_mbFjxVsa1NotqLJ0ruWvFJ8msX7jFxvejadQ2ENWtNyIo-_WDWQo4SBWvIeozf8R-9J4iYvgEAAA==

Logs

n/a

System Info

REPL

Severity

annoyance

geoffrich avatar Dec 08 '23 02:12 geoffrich

The issue is still here. Very annoying

Nelhoa avatar May 01 '24 09:05 Nelhoa

I found a (slightly hacky?) workaround for this problem. We can use untrack in this case to remove the warning but keep the behaviour the same. untrack docs

<script>
	import { tweened } from 'svelte/motion';
	import { untrack } from 'svelte';
	
	let count = $state(1);
	let doubled = $derived(count * 2);
	let tweenedDouble = tweened(untrack(() => doubled));

	$effect(() => {
		tweenedDouble.set(doubled);
	})

	function increment() {
		count += 1;
	}
</script>

<p>{$tweenedDouble.toFixed(2)}</p>
<button onclick={increment}>
	clicks: {count}
</button>

Laurens256 avatar Jul 07 '24 16:07 Laurens256