Examples
Six tiny Svelte examples that exercise the things you do every day — reactive declarations, derived stores, action directives, two-way binding, and slot props. Each is short enough to lift into a real project.
Six idiomatic Svelte snippets
EXAMPLE
<!-- ============================================================
Example 1 — Reactive declaration ($:)
============================================================ -->
<script>
let qty = 1;
let price = 19.95;
$: total = qty * price; // recomputes when qty or price changes
$: console.log('total now', total);
</script>
<input type='number' bind:value={qty}>
<p>Total: $ {total.toFixed(2)}</p>
<!-- ============================================================
Example 2 — Custom store (writable + derived)
============================================================ -->
<!-- src/lib/cart.ts -->
<script context='module'>
import { writable, derived } from 'svelte/store';
export const cart = writable([]);
export const totalCents = derived(cart, (items) =>
items.reduce((s, i) => s + i.qty * i.priceCents, 0));
export function add(item) {
cart.update((c) => [...c, item]);
}
</script>
<!-- ============================================================
Example 3 — Action directive (use:)
============================================================ -->
<script>
function clickOutside(node, callback) {
function onClick(e) { if (!node.contains(e.target)) callback(); }
document.addEventListener('click', onClick);
return { destroy() { document.removeEventListener('click', onClick); } };
}
let open = true;
</script>
{#if open}
<div use:clickOutside={() => (open = false)} class='popover'>
Click outside to dismiss
</div>
{/if}
<!-- ============================================================
Example 4 — Two-way binding for forms
============================================================ -->
<script>
let email = '';
let agree = false;
$: invalid = !email.includes('@') || !agree;
</script>
<input type='email' bind:value={email}>
<label><input type='checkbox' bind:checked={agree}> I agree</label>
<button disabled={invalid}>Submit</button>
<!-- ============================================================
Example 5 — Slot props (let:something)
============================================================ -->
<!-- Avatar.svelte -->
<script>
export let name = '';
</script>
<slot {name} initials={name.split(' ').map((p) => p[0]).join('')} />
<!-- App.svelte -->
<Avatar name='Alice Cooper' let:initials let:name>
<div class='avatar'>{initials}</div>
<span>{name}</span>
</Avatar>
<!-- ============================================================
Example 6 — Lifecycle + cleanup
============================================================ -->
<script>
import { onMount, onDestroy } from 'svelte';
let now = new Date();
let timer;
onMount(() => {
timer = setInterval(() => (now = new Date()), 1000);
});
onDestroy(() => clearInterval(timer));
</script>
<time>{now.toLocaleTimeString()}</time>
<!-- ============================================================
Patterns to internalise
============================================================ -->
<!-- - Reactive ($:) over manual subscription -->
<!-- - Derived stores beat duplicated reactive blocks -->
<!-- - Actions for low-level DOM concerns (focus, click-outside, IO) -->
<!-- - Slot props for inversion of control in 'render-prop' style -->
<!-- - onMount + onDestroy for any subscription / listener you create -->
Why it matters
Reach for derived stores whenever a value can be computed from other stores. The reactivity graph stays small and explicit, components stay dumb, and the moment you swap a source store the entire dependent chain updates without a single line of subscription glue.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…