effect-active
ComputerGuy 2 months ago
parent 794a162e12
commit 9ae4a65c4a

@ -255,6 +255,30 @@ const destroy = $effect.root(() => {
destroy();
```
## `$effect.active`
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`.
```svelte
<script>
console.log('in component setup', $effect.active()); // true
function onclick() {
console.log('after component setup', $effect.active()); // false
}
function ondblclick() {
$effect.root(() => {
console.log('in root effect', $effect.active()); // true
return () => {
console.log('in effect teardown', $effect.active()); // false
}
})();
}
</script>
<button {onclick}>Click me!</button>
<button {ondblclick}>Click me twice!</button>
```
## When not to use `$effect`
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...

@ -48,6 +48,8 @@ import { Batch, schedule_effect } from './batch.js';
import { flatten } from './async.js';
/**
* If an effect can be created in the current context, `VALID_EFFECT_PARENT` is returned.
* If not, a value indicating why is returned.
* @returns {number}
*/
function active_root_effect() {

Loading…
Cancel
Save