From a84504132ca8fe58b1aecdff959811f0dcc395a3 Mon Sep 17 00:00:00 2001 From: frankfmy Date: Fri, 6 Feb 2026 17:53:10 +0100 Subject: [PATCH] docs: add description for derived_references_self error Explain direct and indirect self-referencing derived cycles, with examples and guidance on breaking the cycle using $state. Closes #17481 --- .../98-reference/.generated/client-errors.md | 27 +++++++++++++++++++ .../svelte/messages/client-errors/errors.md | 27 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/documentation/docs/98-reference/.generated/client-errors.md b/documentation/docs/98-reference/.generated/client-errors.md index 8601a728a7..f4679a5b7b 100644 --- a/documentation/docs/98-reference/.generated/client-errors.md +++ b/documentation/docs/98-reference/.generated/client-errors.md @@ -52,6 +52,33 @@ See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-long A derived value cannot reference itself recursively ``` +This error occurs when a `$derived` value reads itself during evaluation, either directly or through a chain of other derived values. + +```js +let count = $state(0); + +// directly references itself +let total = $derived(total + count); +``` + +The cycle can also be indirect: + +```js +let a = $derived(b + 1); +let b = $derived(a + 1); +``` + +To fix this, identify which value in the chain should be the source of truth and make it a `$state` instead, updating it explicitly (for example in an event handler): + +```js +let count = $state(0); +let total = $state(0); + +function add() { + total += count; +} +``` + ### each_key_duplicate ``` diff --git a/packages/svelte/messages/client-errors/errors.md b/packages/svelte/messages/client-errors/errors.md index bedf6db0a5..2a37ca2b57 100644 --- a/packages/svelte/messages/client-errors/errors.md +++ b/packages/svelte/messages/client-errors/errors.md @@ -36,6 +36,33 @@ See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-long > A derived value cannot reference itself recursively +This error occurs when a `$derived` value reads itself during evaluation, either directly or through a chain of other derived values. + +```js +let count = $state(0); + +// directly references itself +let total = $derived(total + count); +``` + +The cycle can also be indirect: + +```js +let a = $derived(b + 1); +let b = $derived(a + 1); +``` + +To fix this, identify which value in the chain should be the source of truth and make it a `$state` instead, updating it explicitly (for example in an event handler): + +```js +let count = $state(0); +let total = $state(0); + +function add() { + total += count; +} +``` + ## each_key_duplicate > Keyed each block has duplicate key at indexes %a% and %b%