Skip to content

Commit 9ae4a65

Browse files
committed
add docs
1 parent 794a162 commit 9ae4a65

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,30 @@ const destroy = $effect.root(() => {
255255
destroy();
256256
```
257257

258+
## `$effect.active`
259+
260+
The `$effect.active` rune is an advanced feature that indicates whether or not an effect or [async `$derived`](await-expressions) can be created in the current context. To improve performance and memory efficiency, effects and async deriveds can only be created when a root effect is active. Root effects are created during component setup, but they can also be programmatically created via `$effect.root`.
261+
262+
```svelte
263+
<script>
264+
console.log('in component setup', $effect.active()); // true
265+
266+
function onclick() {
267+
console.log('after component setup', $effect.active()); // false
268+
}
269+
function ondblclick() {
270+
$effect.root(() => {
271+
console.log('in root effect', $effect.active()); // true
272+
return () => {
273+
console.log('in effect teardown', $effect.active()); // false
274+
}
275+
})();
276+
}
277+
</script>
278+
<button {onclick}>Click me!</button>
279+
<button {ondblclick}>Click me twice!</button>
280+
```
281+
258282
## When not to use `$effect`
259283

260284
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...

packages/svelte/src/internal/client/reactivity/effects.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ import { Batch, schedule_effect } from './batch.js';
4848
import { flatten } from './async.js';
4949

5050
/**
51+
* If an effect can be created in the current context, `VALID_EFFECT_PARENT` is returned.
52+
* If not, a value indicating why is returned.
5153
* @returns {number}
5254
*/
5355
function active_root_effect() {

0 commit comments

Comments
 (0)