Performance: Middleware patterns with hooks
This affects the responsiveness and load time by controlling how code runs before and after component rendering.
import { onMount } from 'svelte'; onMount(async () => { await heavyAsyncTask(); });
import { onMount } from 'svelte'; onMount(() => { heavySyncTask(); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous tasks in onMount | Minimal | 0 but blocks JS thread | High due to blocking | [X] Bad |
| Async tasks in onMount | Minimal | 0 | Low | [OK] Good |
| Multiple separate beforeUpdate hooks updating state | Multiple | 2+ | High | [X] Bad |
| Single beforeUpdate hook batching state updates | Multiple | 1 | Medium | [OK] Good |
onMount runsonMount runs once right after the component is added to the page.beforeUpdate and afterUpdate run on updates, onDestroy runs when component is removed.onMount -> Option BonMount [OK]onMount for code after component loads [OK]onMount with beforeUpdateonDestroy to run code on loadafterUpdate runs only onceonDestroy hook in a Svelte component?onDestroy as named exports from 'svelte'.onDestroy(() => { ... }).import { beforeUpdate, afterUpdate } from 'svelte';
beforeUpdate(() => console.log('Before update'));
afterUpdate(() => console.log('After update'));
let count = 0;
function increment() {
count += 1;
}beforeUpdate runs before every DOM update, afterUpdate runs after every DOM update.increment() changes count, triggering component update and both hooks logging messages.onDestroy? import { onDestroy } from 'svelte';
onDestroy = () => {
console.log('Cleanup');
};onDestroy instead of calling it with a callback.onDestroy must be called like onDestroy(() => { ... }) to register cleanup.afterUpdate runs after the DOM updates, perfect for logging post-change.onDestroy runs when component is removed, ideal for cleanup tasks.afterUpdate to log after DOM changes; use onDestroy for cleanup -> Option APass the test and this pattern moves unknown