Middleware patterns with hooks help you run code before or after certain actions in your app. This lets you add features like logging, validation, or data fetching in a clean way.
Middleware patterns with hooks in Svelte
import { beforeUpdate, afterUpdate, onMount, onDestroy } from 'svelte'; // Example middleware hook usage onMount(() => { // Code to run when component appears }); beforeUpdate(() => { // Code to run before DOM updates }); afterUpdate(() => { // Code to run after DOM updates }); onDestroy(() => { // Cleanup code when component is removed });
Hooks like onMount and onDestroy let you run code at specific times in a component's life.
You can think of these hooks as middleware that runs around your component's main work.
import { onMount } from 'svelte'; onMount(() => { console.log('Component loaded'); });
import { beforeUpdate } from 'svelte'; beforeUpdate(() => { console.log('About to update DOM'); });
import { onDestroy } from 'svelte'; onDestroy(() => { console.log('Component is gone, cleaning up'); });
This Svelte component uses middleware hooks to log messages at different times: when it loads, before and after updates, and when it is removed. Clicking the button changes the count and triggers the update hooks.
<script> import { onMount, beforeUpdate, afterUpdate, onDestroy } from 'svelte'; let count = 0; onMount(() => { console.log('Component mounted'); }); beforeUpdate(() => { console.log('Before update: count is', count); }); afterUpdate(() => { console.log('After update: count is', count); }); onDestroy(() => { console.log('Component destroyed'); }); function increment() { count += 1; } </script> <button on:click={increment} aria-label="Increment count">Increment</button> <p>Count: {count}</p>
Hooks run in the order you add them, so plan your middleware carefully.
Use onDestroy to clean up timers or subscriptions to avoid memory leaks.
Middleware hooks help keep your component code clean and focused on UI.
Middleware hooks let you run code at key moments in a component's life.
Use onMount, beforeUpdate, afterUpdate, and onDestroy for middleware patterns.
This helps add features like logging, validation, and cleanup in a neat way.
Practice
Solution
Step 1: Understand when
onMountrunsonMountruns once right after the component is added to the page.Step 2: Compare with other hooks
beforeUpdateandafterUpdaterun on updates,onDestroyruns when component is removed.Final Answer:
onMount-> Option BQuick Check:
Run code after component appears =onMount[OK]
onMount for code after component loads [OK]- Confusing
onMountwithbeforeUpdate - Using
onDestroyto run code on load - Thinking
afterUpdateruns only once
onDestroy hook in a Svelte component?Solution
Step 1: Check correct import syntax
Svelte exports hooks likeonDestroyas named exports from 'svelte'.Step 2: Verify usage
The hook is called as a function with a callback:onDestroy(() => { ... }).Final Answer:
import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ }); -> Option DQuick Check:
Named import + callback function = import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ }); [OK]
- Using default import instead of named import
- Importing from wrong path like 'svelte/hooks'
- Assigning hook to a variable instead of calling it
import { beforeUpdate, afterUpdate } from 'svelte';
beforeUpdate(() => console.log('Before update'));
afterUpdate(() => console.log('After update'));
let count = 0;
function increment() {
count += 1;
}Solution
Step 1: Understand when hooks run
beforeUpdateruns before every DOM update,afterUpdateruns after every DOM update.Step 2: Analyze increment effect
Callingincrement()changescount, triggering component update and both hooks logging messages.Final Answer:
Before update\nAfter update each time increment() is called -> Option CQuick Check:
Hooks run on every update = Before update\nAfter update each time increment() is called [OK]
- Thinking hooks run only once on mount
- Assuming logs happen without calling increment()
- Confusing beforeUpdate and afterUpdate timing
onDestroy? import { onDestroy } from 'svelte';
onDestroy = () => {
console.log('Cleanup');
};Solution
Step 1: Check how onDestroy is used
The code assigns a function toonDestroyinstead of calling it with a callback.Step 2: Correct usage
onDestroymust be called likeonDestroy(() => { ... })to register cleanup.Final Answer:
Assigning a function to onDestroy instead of calling it -> Option AQuick Check:
Use onDestroy(callback), not assignment [OK]
- Assigning instead of calling the hook
- Thinking arrow functions are disallowed
- Believing onDestroy must be inside onMount
Solution
Step 1: Identify hook for after DOM update
afterUpdateruns after the DOM updates, perfect for logging post-change.Step 2: Determine cleanup hook
onDestroyruns when component is removed, ideal for cleanup tasks.Final Answer:
UseafterUpdateto log after DOM changes; useonDestroyfor cleanup -> Option AQuick Check:
Log after DOM update = afterUpdate; cleanup = onDestroy [OK]
- Using beforeUpdate to log after DOM changes
- Trying to cleanup inside afterUpdate
- Confusing onMount with update hooks
Ready to prove it?
Pass the test and this pattern moves unknown
