Discover how middleware hooks can save you from repeating the same code everywhere!
Why Middleware patterns with hooks in Svelte? - Purpose & Use Cases
Imagine you have a Svelte app where you want to run some code before and after certain actions, like logging user activity or checking permissions, but you write this logic inside every component manually.
Manually adding the same checks or side effects in every component is tiring, easy to forget, and makes your code messy and hard to maintain.
Middleware patterns with hooks let you insert reusable code that runs automatically at key points, keeping your components clean and your logic centralized.
function save() {
if (!userIsLoggedIn()) return;
logAction('save');
// save data
}useMiddleware(() => {
if (!userIsLoggedIn()) return false;
logAction('save');
});
function save() {
// save data
}This makes your app easier to extend, debug, and keep consistent by separating concerns clearly.
Think of a security guard who checks IDs at the entrance (middleware) so every visitor inside the building is already verified without each room needing its own guard.
Manual repetition of checks clutters code and causes mistakes.
Middleware with hooks centralizes shared logic cleanly.
It improves app maintainability and consistency.
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
