Skip to content

Commit ce2566d

Browse files
authored
docs: simplify $effect.tracking() docs (#14939)
1 parent 9c20eb4 commit ce2566d

File tree

1 file changed

+1
-47
lines changed

1 file changed

+1
-47
lines changed

documentation/docs/02-runes/04-$effect.md

Lines changed: 1 addition & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -193,53 +193,7 @@ The `$effect.tracking` rune is an advanced feature that tells you whether or not
193193
<p>in template: {$effect.tracking()}</p> <!-- true -->
194194
```
195195

196-
This allows you to (for example) add things like subscriptions without causing memory leaks, by putting them in child effects. Here's a `readable` function that listens to changes from a callback function as long as it's inside a tracking context:
197-
198-
```ts
199-
import { tick } from 'svelte';
200-
201-
export default function readable<T>(
202-
initial_value: T,
203-
start: (callback: (update: (v: T) => T) => T) => () => void
204-
) {
205-
let value = $state(initial_value);
206-
207-
let subscribers = 0;
208-
let stop: null | (() => void) = null;
209-
210-
return {
211-
get value() {
212-
// If in a tracking context ...
213-
if ($effect.tracking()) {
214-
$effect(() => {
215-
// ...and there's no subscribers yet...
216-
if (subscribers === 0) {
217-
// ...invoke the function and listen to changes to update state
218-
stop = start((fn) => (value = fn(value)));
219-
}
220-
221-
subscribers++;
222-
223-
// The return callback is called once a listener unlistens
224-
return () => {
225-
tick().then(() => {
226-
subscribers--;
227-
// If it was the last subscriber...
228-
if (subscribers === 0) {
229-
// ...stop listening to changes
230-
stop?.();
231-
stop = null;
232-
}
233-
});
234-
};
235-
});
236-
}
237-
238-
return value;
239-
}
240-
};
241-
}
242-
```
196+
It is used to implement abstractions like [`createSubscriber`](/docs/svelte/svelte-reactivity#createSubscriber), which will create listeners to update reactive values but _only_ if those values are being tracked (rather than, for example, read inside an event handler).
243197

244198
## `$effect.root`
245199

0 commit comments

Comments
 (0)