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.