Chapter 4: Building Components
Component Lifecycle
Every Svelte component moves through mounting, updating, and destruction phases. Importing lifecycle hooks from svelte lets you integrate with browser APIs, timers, or third-party DOM libraries without leaking resources when a component leaves the screen:
onMount: Runs once after the component is first rendered into the DOM. Ideal for reading element dimensions, starting subscriptions, or fetching initial client data. Returning a function fromonMountautomatically registers it as a cleanup callback.beforeUpdate: Runs immediately before the DOM updates after state changes—useful for capturing scroll position before new list items are inserted.afterUpdate: Runs right after the DOM syncs with the latest state, allowing you to restore scroll position or focus.onDestroy: Runs when the component is unmounted; always clear intervals, event listeners, or WebSocket connections here to prevent memory leaks.
<script>
import { onMount } from 'svelte';
let seconds = 0;
onMount(() => {
const timer = setInterval(() => {
seconds += 1;
}, 1000);
// Returned cleanup runs automatically when the component unmounts
return () => clearInterval(timer);
});
</script>
<p>Elapsed: {seconds}s</p>
Using Slots
Passing HTML or nested components through props quickly becomes rigid. Svelte's <slot> element acts as a placeholder where parent components inject arbitrary markup, keeping wrapper components focused on layout, borders, and spacing. You can also place fallback content inside <slot>...</slot> that renders when the caller provides nothing:
<!-- Card.svelte -->
<section class="card">
<slot>
<p>No content provided.</p>
</slot>
</section>
<style>
.card {
border: 1px solid #334155;
border-radius: 0.5rem;
padding: 1rem;
}
</style>
Any markup placed between the opening and closing <Card> tags flows into that default slot while still retaining access to the parent component's scope:
<Card>
<h2>Account Summary</h2>
<p>This content is injected into the default slot.</p>
</Card>
Named Slots
When a layout shell has distinct regions—such as a header, main body, and action footer—use named slots (<slot name="...">) so callers target each region explicitly regardless of element order:
<!-- Layout.svelte -->
<div class="panel">
<header><slot name="header"></slot></header>
<main><slot></slot></main>
<footer><slot name="footer"></slot></footer>
</div>
Callers assign elements to a named slot using the slot="..." attribute; any element without a slot attribute goes into the unnamed default slot:
<Layout>
<h3 slot="header">Billing Settings</h3>
<p>Manage your payment methods and invoices.</p>
<button slot="footer" type="button">Save changes</button>
</Layout>
Event Forwarding
While props carry data downward, events communicate user intent upward. A child component can create a typed dispatcher with createEventDispatcher() to emit domain events with a payload, or forward a native DOM event like on:click (with no handler value) so parent components can listen directly:
<script>
import { createEventDispatcher } from 'svelte';
export let itemId;
const dispatch = createEventDispatcher();
function handleArchive() {
// Emit a domain event with structured detail instead of coupling to parent logic
dispatch('archive', { id: itemId });
}
</script>
<button type="button" on:click={handleArchive}>Archive</button>
Practice: Create a reusable ModalShell.svelte component with named header, default body, and footer slots, a cleanup-safe Escape key listener registered in onMount, and a custom close event dispatched to the parent.