0
0
Svelteframework~5 mins

Middleware patterns with hooks in Svelte

Choose your learning style9 modes available
Introduction

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.

You want to check user permissions before showing a page.
You need to log user actions like clicks or form submissions.
You want to fetch data automatically when a component loads.
You want to modify or validate data before saving it.
You want to run cleanup code when a component is removed.
Syntax
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.

Examples
This runs code once when the component appears on the page.
Svelte
import { onMount } from 'svelte';

onMount(() => {
  console.log('Component loaded');
});
This runs code right before the component updates the page.
Svelte
import { beforeUpdate } from 'svelte';

beforeUpdate(() => {
  console.log('About to update DOM');
});
This runs cleanup code when the component is removed from the page.
Svelte
import { onDestroy } from 'svelte';

onDestroy(() => {
  console.log('Component is gone, cleaning up');
});
Sample Program

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.

Svelte
<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>
OutputSuccess
Important Notes

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.

Summary

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.