From ee04f973b29367769b702e3b60b34191a1f24ac5 Mon Sep 17 00:00:00 2001 From: Simon H <5968653+dummdidumm@users.noreply.github.com> Date: Mon, 4 Mar 2024 14:59:40 +0100 Subject: [PATCH] docs: enhance `$effect` documentation (#10680) - explain when not to use `$effect`, closes #10193 - explain that only synchronous reads are tracked, closes #10475 - explain nuance around reruns and object reads, closes #10392 --- .../routes/docs/content/01-api/02-runes.md | 194 ++++++++++++++++-- 1 file changed, 180 insertions(+), 14 deletions(-) diff --git a/sites/svelte-5-preview/src/routes/docs/content/01-api/02-runes.md b/sites/svelte-5-preview/src/routes/docs/content/01-api/02-runes.md index 379336a993..850daabb45 100644 --- a/sites/svelte-5-preview/src/routes/docs/content/01-api/02-runes.md +++ b/sites/svelte-5-preview/src/routes/docs/content/01-api/02-runes.md @@ -161,24 +161,101 @@ In essence, `$derived(expression)` is equivalent to `$derived.by(() => expressio To run side-effects like logging or analytics whenever some specific values change, or when a component is mounted to the DOM, we can use the `$effect` rune: -```diff +```svelte + + + + +

{count} doubled is {doubled}

+``` + +`$effect` will automatically subscribe to any `$state` or `$derived` values it reads _synchronously_ and reruns whenever their values change — that means, values after an `await` or inside a `setTimeout` will _not_ be tracked. `$effect` will run after the DOM has been updated. + +```svelte + + + + +

{count} doubled is {doubled}

+``` + +An effect only reruns when the object it reads changes, not when a property inside it changes. If you want to react to _any_ change inside an object for inspection purposes at dev time, you may want to use [`inspect`](#inspect). + +```svelte + + + + +

{count} doubled is {doubled}

+``` + +You can return a function from `$effect`, which will run immediately before the effect re-runs, and before it is destroyed. + +```svelte