docs: document event delegation and effect deferral (#11747)

* docs: document event delegation and effect deferral

* document flushSync
pull/11755/head
Rich Harris 2 months ago committed by GitHub
parent 8459098c05
commit 24151c4e9c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -6,6 +6,29 @@ As well as runes, Svelte 5 introduces a handful of new things you can import, al
## `svelte`
### `flushSync`
Forces any pending effects (including DOM updates) to be applied immediately, rather than in the future. This is mainly useful in a testing context — you'll rarely need it in application code.
```svelte
<script>
import { flushSync } from 'svelte';
let count = $state(0);
let element;
function onclick() {
flushSync(() => (count += 1));
// without `flushSync`, the DOM would be updated in the future
console.log(element.textContent === String(count));
}
</script>
<span bind:this={element}>{count}</span>
<button {onclick}>update</button>
```
### `mount`
Instantiates a component and mounts it to the given target:

@ -152,6 +152,25 @@ In Svelte 4, doing the following triggered reactivity:
This is because the Svelte compiler treated the assignment to `foo.value` as an instruction to update anything that referenced `foo`. In Svelte 5, reactivity is determined at runtime rather than compile time, so you should define `value` as a reactive `$state` field on the `Foo` class. Wrapping `new Foo()` with `$state(...)` will have no effect — only vanilla objects and arrays are made deeply reactive.
### Events and bindings use delegated handlers
Event handlers added to elements with things like `onclick={...}` or `bind:value={...}` use _delegated_ handlers where possible. This means that Svelte attaches a single event handler to a root node rather than using `addEventListener` on each individual node, resulting in better performance and memory usage.
Additionally, updates that happen inside event handlers will not be reflected in the DOM (or in `$effect(...)`) until the browser has had a chance to repaint. This ensures that your app stays responsive, and your Core Web Vitals (CWV) aren't penalised.
In very rare cases you may need to force updates to happen immediately. You can do this with `flushSync`:
```diff
<script>
+ import { flushSync } from 'svelte';
function onclick() {
- update_something();
+ flushSync(() => update_something());
}
</script>
```
## Other breaking changes
### Stricter `@const` assignment validation

Loading…
Cancel
Save