docs: tweak untrack description, provide an example of usage (#14085)

* docs: tweak untrack description, provide an example of usage

* link to untrack

* add derived docs too
pull/14095/head
Rich Harris 2 months ago committed by GitHub
parent 2ab70041fd
commit 6a2c28c590
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -45,3 +45,9 @@ Sometimes you need to create complex derivations that don't fit inside a short e
```
In essence, `$derived(expression)` is equivalent to `$derived.by(() => expression)`.
## Understanding dependencies
Anything read synchronously inside the `$derived` expression (or `$derived.by` function body) is considered a _dependency_ of the derived state. When the state changes, the derived will be marked as _dirty_ and recalculated when it is next read.
To exempt a piece of state from being treated as a dependency, use [`untrack`](svelte#untrack).

@ -2,7 +2,7 @@
title: $effect
---
Effects are what make your application _do things_. When Svelte runs an effect function, it tracks which pieces of state (and derived state) are accessed, and re-runs the function when that state later changes.
Effects are what make your application _do things_. When Svelte runs an effect function, it tracks which pieces of state (and derived state) are accessed (unless accessed inside [`untrack`](svelte#untrack)), and re-runs the function when that state later changes.
Most of the effects in a Svelte app are created by Svelte itself — they're the bits that update the text in `<h1>hello {name}!</h1>` when `name` changes, for example.

@ -831,7 +831,17 @@ export function invalidate_inner_signals(fn) {
}
/**
* Use `untrack` to prevent something from being treated as an `$effect`/`$derived` dependency.
* When used inside a [`$derived`](https://svelte.dev/docs/svelte/$derived) or [`$effect`](https://svelte.dev/docs/svelte/$effect),
* any state read inside `fn` will not be treated as a dependency.
*
* ```ts
* $effect(() => {
* // this will run when `data` changes, but not when `time` changes
* save(data, {
* timestamp: untrack(() => time)
* });
* });
* ```
* @template T
* @param {() => T} fn
* @returns {T}

@ -455,7 +455,17 @@ declare module 'svelte' {
* */
export function tick(): Promise<void>;
/**
* Use `untrack` to prevent something from being treated as an `$effect`/`$derived` dependency.
* When used inside a [`$derived`](https://svelte.dev/docs/svelte/$derived) or [`$effect`](https://svelte.dev/docs/svelte/$effect),
* any state read inside `fn` will not be treated as a dependency.
*
* ```ts
* $effect(() => {
* // this will run when `data` changes, but not when `time` changes
* save(data, {
* timestamp: untrack(() => time)
* });
* });
* ```
* */
export function untrack<T>(fn: () => T): T;
/**

Loading…
Cancel
Save