Svelte
A javascript framework is essentially a tool thats used for web development and makes our lives as devs alot easier. Frameworks simplify complex tasks like manipulating DOM elements, managing state and routing.
Svelte is one of many javascript frameworks, but it is the one that our team uses.
Why use Svelte?
In addition to being faster than other frameworks (due to the absence of a virtual DOM), Svelte offers a clean, component based experience, with other features that make developing websites much easier. For example, an in-built reactivity system allows for code that doesn't have to go through state management, leading to variables being tracked and updated to the UI as they updated themselves.
This makes developing in Svelte simpler and more intuitive.
Core Concepts in Svelte
1. Reactivity
Svelte 3: Used the $: syntax for reactive declarations.
let count = 0;
$: double = count * 2;
Svelte 5: Introduces the $state and effect() system for
finer reactivity control.
let count = $state(0);
let double = $derived(() => count * 2);
effect(() => {
console.log('Count changed to', count);
});
Purpose:
$statecreates reactive state variables.$deriveddefines computed values.effect()runs side effects when dependencies change.
2. Component Props
Svelte 3: Declared props using export let.
export let name;
Svelte 5: Similar, but $props() is available for destructuring.
const { name } = $props();
Purpose:
- Allows props to be destructured directly.
- Reduces boilerplate in larger components.
3. Stores (State Management)
Svelte 3: Used writable, readable, and derived stores from
svelte/store.
import { writable } from 'svelte/store';
export const count = writable(0);
Svelte 5: Still compatible, but you can now use $state directly in
components --- no external store needed for local state.
Comparison:
- Svelte 3 required stores for shared/global state.
- Svelte 5 integrates reactivity natively, reducing dependence on stores.
4. Events and Bindings
Event handling:
<button on:click={() => count++}>Increment</button>
becomes
<button onclick={handler}>
or
<button {onclick}>
Bindings (pretty much the same, except uses runes to define reactive variables):
<input bind:value={name}>
5. Slots and Component Composition
Svelte 3 vs 5: Slots get replaced by the use of snippets and {@render} tags
<slot name="header">Default Header</slot>
becomes
{#snippet header()}
<h1>Default Header</h1>
{/snippet}