From 14492ad639303864c0e916cffc9ba5ac3751807c Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 11 Mar 2024 14:43:47 -0400 Subject: [PATCH] docs: simplify when-not-to-use-effects (#10749) --------- Co-authored-by: Rich Harris Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com> --- .../routes/docs/content/01-api/02-runes.md | 38 +++++-------------- 1 file changed, 9 insertions(+), 29 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 e4c167f8e8..0e158c179d 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 @@ -267,53 +267,33 @@ You can return a function from `$effect`, which will run immediately before the ``` -> `$effect` was designed for managing side effects such as logging or connecting to external systems like third party libraries that have an imperative API. If you're managing state or dataflow, you should use it with caution – most of the time, you're better off using a different pattern. Below are some use cases and what to use instead. +### When not to use `$effect` -If you update `$state` inside an `$effect`, you most likely want to use `$derived` instead. +In general, `$effect` is best considered something of an escape hatch — useful for things like analytics and direct DOM manipulation — rather than a tool you should use frequently. In particular, avoid using it to synchronise state. Instead of this... ```svelte - - - - ``` -This also applies to more complex calculations that require more than a simple expression and write to more than one variable. In these cases, you can use `$derived.by`. +...do this: ```svelte - - - - ``` +> For things that are more complicated than a simple expression like `count * 2`, you can also use [`$derived.by`](#$derived-by). + When reacting to a state change and writing to a different state as a result, think about if it's possible to use callback props instead. ```svelte