Frontend

Svelte: Reactive UIs with No Virtual DOM

Mayur Dabhi
Mayur Dabhi
May 30, 2026
14 min read

You build a small embeddable widget, maybe a signup form or a pricing calculator, and it has to drop into someone else's page. You reach for React out of habit, and before you've written any real logic the bundle already carries React and ReactDOM. Then you add useMemo and useCallback just to stop a list from re-rendering on every keystroke. For something this small, that's a lot of machinery.

Svelte handles this differently. Instead of shipping a runtime that diffs a Virtual DOM in the browser, it compiles your components into plain JavaScript at build time that updates the DOM directly. This post walks through how that works, the component syntax, reactivity, stores, transitions, and SvelteKit for full-stack apps, plus the trade-offs that should make you think twice before picking it.

Is Anyone Using It in Production?

Yes. Svelte regularly scores near the top for developer satisfaction in the Stack Overflow and State of JS surveys, and The New York Times used it for interactive graphics (Rich Harris built Svelte while working there). SvelteKit has been stable since v1.0 in late 2022, so it's a reasonable production choice, not an experiment.

The Philosophy Behind Svelte

React, Vue, and Angular all ship a JavaScript runtime to the browser that manages reactivity. When state changes, the framework builds a new Virtual DOM tree, diffs it against the old one, and applies the changes to the real DOM. It works well, but you pay for it:

Rich Harris's idea with Svelte was simple: what if most of the framework didn't need to exist at runtime? The compiler does the work up front, turning your .svelte files into vanilla JavaScript that touches exactly the DOM nodes that depend on a changed value. There's still a small amount of shared helper code, but no diffing and no reconciliation step.

React / Vue Approach Source Code Bundle App + Runtime (~40KB) 🌐 Browser Runtime Virtual DOM diff → real DOM update Svelte Approach Source Code Svelte Compiler Runs at build time Vanilla JS Direct DOM mutations 🌐 No framework runtime in browser Svelte moves framework work from runtime to compile time

Svelte's compile-time approach vs. traditional runtime frameworks

Svelte vs React vs Vue: A Comparison

The bundle numbers below are rough gzipped figures for a minimal app. They shift between versions, and the gap narrows as your own code grows, because Svelte's compiled output per component is larger than the equivalent JSX.

Feature Svelte React Vue 3
Approach Compile-time Runtime (Virtual DOM) Runtime (Virtual DOM)
Bundle size (Hello World) ~4KB ~42KB ~22KB
Reactivity Assignments trigger updates useState / hooks ref() / reactive()
Learning curve Low (HTML-like syntax) Medium (JSX, hooks) Low-Medium
Full-stack solution SvelteKit Next.js Nuxt.js
TypeScript support Built-in Excellent Excellent

Setting Up Your First Svelte Project

For most projects I'd start with SvelteKit, Svelte's official application framework (roughly what Next.js is to React). If you only need a client-side SPA, scaffolding with Vite directly is fine too.

1

Create a SvelteKit Project

Use the official SvelteKit template. It gives you routing, server-side rendering, and TypeScript out of the box. Heads up: newer releases moved the scaffolder to npx sv create, and running npm create svelte@latest today just prints a deprecation notice pointing you there.

Terminal
# Create a new SvelteKit project
npm create svelte@latest my-svelte-app

# Follow the prompts:
# - Template: Skeleton project
# - TypeScript: Yes (recommended)
# - ESLint, Prettier: Yes

cd my-svelte-app
npm install
npm run dev
2

Alternative: Pure Svelte with Vite

For an SPA without server-side rendering, use the Vite template. It's lighter, but you lose SvelteKit's routing and SSR.

Terminal: Vite + Svelte
# Using Vite's Svelte template
npm create vite@latest my-svelte-spa -- --template svelte-ts

cd my-svelte-spa
npm install
npm run dev
3

Explore the Project Structure

Open the project in your editor. In SvelteKit, all routes live in src/routes/. Your first component to edit is src/routes/+page.svelte.

VS Code Setup

Install the official Svelte for VS Code extension (svelte.svelte-vscode) for syntax highlighting, IntelliSense, and formatting. It runs the Svelte Language Server, so you get type errors inside .svelte files as you type. In CI, run svelte-check as well, because plain tsc doesn't understand .svelte files.

Anatomy of a Svelte Component

Each .svelte file has up to three parts: a <script> block for logic, a <style> block for CSS (scoped to the component automatically), and the HTML template. Unlike JSX, you write actual HTML. No className instead of class, no htmlFor instead of for.

Component Structure

Counter.svelte
<script lang="ts">
    // Reactive variable: just a regular let declaration
    let count: number = 0;

    function increment() {
        count += 1;  // This assignment triggers a DOM update!
    }

    function reset() {
        count = 0;
    }
</script>

<!-- Template: plain HTML with {expressions} -->
<div class="counter">
    <h2>Count: {count}</h2>
    <button on:click={increment}>Increment</button>
    <button on:click={reset} disabled={count === 0}>Reset</button>
</div>

<style>
    /* Styles are scoped automatically, so they won't leak out */
    .counter {
        display: flex;
        flex-direction: column;
        gap: 12px;
        padding: 24px;
    }
    button {
        padding: 8px 16px;
        background: #FF3E00;
        color: white;
        border: none;
        border-radius: 6px;
        cursor: pointer;
    }
</style>

count is just a let variable. No useState hook, no ref() call. The compiler sees which variables the template uses and generates code that updates those DOM nodes whenever the variable is reassigned. count += 1 is all it takes.

Svelte 4 Syntax vs Svelte 5 Runes

The examples here use the Svelte 4 style (let, export let, $:). Svelte 5 introduced runes ($state, $props, $derived, $effect) as the new default. The old syntax still compiles in Svelte 5 components that don't use runes, but you can't mix both styles in one component. If you copy a snippet and get a compiler error about $: not being allowed in runes mode, that's why.

Props and Component Communication

Props are declared with export let. It looks odd at first, but read it as "this variable can be set by the parent component."

Badge.svelte: Defining Props
<script lang="ts">
    // Props are declared with `export let`
    export let label: string;
    export let count: number = 0;        // Default value
    export let variant: 'primary' | 'secondary' = 'primary';
</script>

<span class="badge {variant}">
    {label}
    {#if count > 0}
        <sup>{count}</sup>
    {/if}
</span>

<style>
    .badge { padding: 4px 10px; border-radius: 12px; font-size: 0.85rem; }
    .primary { background: #FF3E00; color: white; }
    .secondary { background: #e0e0e0; color: #333; }
</style>
App.svelte: Using the Badge Component
<script lang="ts">
    import Badge from './Badge.svelte';
    let notifications = 5;
</script>

<Badge label="Inbox" count={notifications} variant="primary" />
<Badge label="Archive" />  <!-- Uses defaults -->

Template Directives

These four blocks cover most of what you'll write day to day:

<!-- if / else if / else -->
{#if user.role === 'admin'}
    <AdminPanel />
{:else if user.role === 'editor'}
    <EditorPanel />
{:else}
    <ReadOnlyView />
{/if}
<!-- each block with index and key -->
{#each products as product, i (product.id)}
    <div class="product-card">
        <span>{i + 1}.</span>
        <h3>{product.name}</h3>
        <p>${product.price}</p>
    </div>
{:else}
    <p>No products found.</p>
{/each}
<script lang="ts">
    async function fetchUser(id: number) {
        const res = await fetch(`/api/users/${id}`);
        return res.json();
    }
    let userPromise = fetchUser(1);
</script>

{#await userPromise}
    <p>Loading...</p>
{:then user}
    <h2>{user.name}</h2>
{:catch error}
    <p class="error">{error.message}</p>
{/await}
<script lang="ts">
    let name = '';
    let agreed = false;
    let selectedColor = 'red';
</script>

<!-- bind:value creates two-way data binding -->
<input bind:value={name} placeholder="Your name" />
<input type="checkbox" bind:checked={agreed} />
<select bind:value={selectedColor}>
    <option value="red">Red</option>
    <option value="blue">Blue</option>
</select>

<p>Hello, {name}! Agreed: {agreed}</p>

Svelte's Reactive Declarations

The $: prefix is technically a JavaScript label, which Svelte borrows for reactive declarations. Any statement prefixed with $: re-runs whenever a variable it references changes. Note that dependencies are worked out at compile time from what appears directly in the statement, so a value read inside a function you call from it won't be tracked.

Reactive Statements

Reactive declarations with $:
<script lang="ts">
    let firstName = 'Mayur';
    let lastName = 'Dabhi';

    // $: creates a reactive declaration that recomputes when deps change
    $: fullName = `${firstName} ${lastName}`;
    $: initials = `${firstName[0]}${lastName[0]}`;

    let items: string[] = [];
    let filter = '';

    // Complex reactive statement: runs when items or filter changes
    $: filteredItems = items.filter(item =>
        item.toLowerCase().includes(filter.toLowerCase())
    );

    // Reactive statement (not just expression)
    $: {
        if (filteredItems.length === 0 && filter !== '') {
            console.log('No items match the filter:', filter);
        }
    }

    // Reactive statement that depends on a condition
    $: document.title = `${filteredItems.length} results for "${filter}"`;
</script>
Arrays and Objects: Mutate by Reassignment

Svelte tracks reactivity through assignments, not mutations. If you do items.push('new item'), Svelte won't detect the change because no assignment occurred. Reassign the array instead: items = [...items, 'new item'], or assign it back to itself after mutating: items.push('x'); items = items;. This trips up a lot of people coming from Vue, where mutations are tracked through proxies.

Svelte Stores: Shared State

Once two components that aren't parent and child need the same state, passing props gets painful. Svelte's answer is stores: small observable objects any component can subscribe to. The API is tiny: writable, readable, and derived.

Creating and Using Stores

stores/cart.ts: Defining a Store
import { writable, derived } from 'svelte/store';

interface CartItem {
    id: number;
    name: string;
    price: number;
    quantity: number;
}

// writable store: can be read and written from anywhere
export const cartItems = writable<CartItem[]>([]);

// derived store: computed from cartItems, updates automatically
export const cartTotal = derived(cartItems, ($items) =>
    $items.reduce((sum, item) => sum + item.price * item.quantity, 0)
);

export const cartCount = derived(cartItems, ($items) =>
    $items.reduce((sum, item) => sum + item.quantity, 0)
);

// Helper functions that update the store
export function addToCart(item: Omit<CartItem, 'quantity'>) {
    cartItems.update(items => {
        const existing = items.find(i => i.id === item.id);
        if (existing) {
            return items.map(i =>
                i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i
            );
        }
        return [...items, { ...item, quantity: 1 }];
    });
}

export function removeFromCart(id: number) {
    cartItems.update(items => items.filter(i => i.id !== id));
}
CartIcon.svelte: Auto-subscribing with $
<script lang="ts">
    import { cartCount, cartTotal, removeFromCart } from '../stores/cart';

    // The $ prefix auto-subscribes to a store.
    // Svelte handles subscribe() and unsubscribe() lifecycle for you.
    // $cartCount and $cartTotal are always the current values.
</script>

<button class="cart-btn">
    Cart ({$cartCount} items) - ${$cartTotal.toFixed(2)}
</button>
writable() cartItems store set / update / subscribe ProductCard.svelte addToCart() CartIcon.svelte $cartCount (reads) CartPage.svelte $cartItems (reads) derived() cartTotal, cartCount Any component can read/write the store, no prop drilling

Stores give you shared state without prop drilling or Context API boilerplate

Stores and SSR Don't Mix Well

A store defined at module level, like cartItems above, is a singleton. In the browser that's fine. On a SvelteKit server, that one instance is shared by every request, so if you write user-specific data into it during SSR, one user's cart can show up in another user's HTML. Keep per-user state in load() data or in context set by a layout, and only put truly global or client-only state in module-level stores.

Built-in Transitions and Animations

In React, animating elements in and out usually means adding Framer Motion or React Spring. Svelte ships transition and animation directives in the box, and they run as CSS animations when elements enter or leave the DOM.

Transitions and Animations
<script lang="ts">
    import { fade, fly, slide, scale } from 'svelte/transition';
    import { flip } from 'svelte/animate';

    let visible = true;
    let items = ['Apple', 'Banana', 'Cherry'];

    function addItem() {
        items = [...items, `Item ${items.length + 1}`];
    }

    function removeItem(index: number) {
        items = items.filter((_, i) => i !== index);
    }
</script>

<button on:click={() => visible = !visible}>Toggle</button>

{#if visible}
    <!-- fade: opacity 0→1 on enter, 1→0 on leave -->
    <div transition:fade={{ duration: 300 }}>
        Fades in and out
    </div>

    <!-- fly: moves from y=50px while fading -->
    <p in:fly="{{ y: 50, duration: 400 }}" out:fade>
        Flies in from below
    </p>
{/if}

<!-- flip animates list reorders smoothly -->
<ul>
    {#each items as item, i (item)}
        <li animate:flip={{ duration: 300 }}>
            {item}
            <button on:click={() => removeItem(i)}>✕</button>
        </li>
    {/each}
</ul>
Custom Transitions

A Svelte transition is just a function that returns { delay, duration, easing, css }, so writing your own is easy. The css field is a function that gets a t value from 0 to 1 and returns a CSS string. That's enough for most custom animations without pulling in another dependency.

SvelteKit: Full-Stack Development

Most real apps need routing, server rendering, and somewhere to put API endpoints. SvelteKit covers all three, much like Next.js does for React, and uses adapters to deploy to Node.js, Cloudflare Workers, Vercel, Netlify, and others.

File-Based Routing

In SvelteKit, every +page.svelte file inside src/routes/ becomes a route. The file system is the router:

File Path URL Route Description
src/routes/+page.svelte / Home page
src/routes/blog/+page.svelte /blog Blog listing
src/routes/blog/[slug]/+page.svelte /blog/:slug Dynamic blog post
src/routes/+layout.svelte All routes Shared layout (nav, footer)
src/routes/api/users/+server.ts /api/users API endpoint

Load Functions and Server-Side Data

SvelteKit separates data fetching from rendering using +page.server.ts (runs only on the server) and +page.ts (runs on both client and server). Data returned from load() is passed as the data prop to your page component.

src/routes/blog/[slug]/+page.server.ts
import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ params, fetch }) => {
    const res = await fetch(`/api/posts/${params.slug}`);

    if (!res.ok) {
        throw error(404, `Post "${params.slug}" not found`);
    }

    const post = await res.json();

    return {
        post,
        // This data is passed as `data` prop to +page.svelte
    };
};
src/routes/blog/[slug]/+page.svelte
<script lang="ts">
    import type { PageData } from './$types';

    // data is automatically typed from the load function
    export let data: PageData;

    const { post } = data;
</script>

<svelte:head>
    <title>{post.title} | My Blog</title>
    <meta name="description" content={post.excerpt} />
</svelte:head>

<article>
    <h1>{post.title}</h1>
    <time datetime={post.publishedAt}>{post.formattedDate}</time>
    <div class="content">{@html post.htmlContent}</div>
</article>
Gotcha: Stale Data When Navigating Between Posts

The const { post } = data; line above has a subtle bug. When you go from /blog/a to /blog/b, SvelteKit reuses the same page component and just passes a new data prop. The script block doesn't run again, so post still holds the first article while the URL has changed. Use $: ({ post } = data); or reference data.post directly in the template.

API Routes with Form Actions

Form actions handle submissions on the server and work with a plain HTML form, no JavaScript required. When JS is available, use:enhance upgrades the form to submit via fetch without a full page reload. You get a form that still works if your bundle fails to load, which is good for accessibility too.

src/routes/contact/+page.server.ts: Form Action
import type { Actions } from './$types';
import { fail, redirect } from '@sveltejs/kit';

export const actions: Actions = {
    default: async ({ request }) => {
        const data = await request.formData();
        const email = data.get('email') as string;
        const message = data.get('message') as string;

        if (!email || !message) {
            return fail(400, { error: 'Email and message are required.' });
        }

        // Send email, save to DB, etc.
        await sendContactEmail({ email, message });

        throw redirect(303, '/contact/success');
    }
};
src/routes/contact/+page.svelte: Enhanced Form
<script lang="ts">
    import { enhance } from '$app/forms';
    import type { ActionData } from './$types';
    export let form: ActionData;
</script>

<!-- use:enhance progressively enhances the form with fetch -->
<form method="POST" use:enhance>
    {#if form?.error}
        <p class="error">{form.error}</p>
    {/if}
    <input name="email" type="email" placeholder="your@email.com" required />
    <textarea name="message" placeholder="Your message..." required></textarea>
    <button type="submit">Send Message</button>
</form>

When I'd Use Svelte (and When I Wouldn't)

Svelte isn't automatically faster for every app. The compile-time approach pays off most when the page is small or the framework cost is a big share of what you ship.

Where I'd reach for it:

  • Embeds and widgets: Anything that loads inside someone else's page, where shipping a whole React runtime for one form is hard to justify
  • Content sites with islands of interactivity: Blogs, docs, and product pages where SvelteKit's SSR or prerendering does most of the work and the client JS stays small
  • UI-heavy animation: Dashboards and visualizations where the built-in transitions save you a dependency
  • Small teams starting fresh: Greenfield apps with no existing React or Vue component library to carry over
Where I'd stick with React (or whatever you already use)

The ecosystem is smaller. You'll find fewer component libraries, fewer Stack Overflow answers, and fewer ready-made integrations. If you depend on a React-specific library (React DnD, a particular charting or rich-text package), you'll be rewriting or wrapping it. On a large app with lots of components, Svelte's per-component output adds up, so the bundle advantage over React shrinks. And for a team that already knows React well, retraining and the Svelte 4 to Svelte 5 syntax shift may cost more than the performance you'd gain.

If you want to see whether it fits, pick something small and self-contained, like an internal tool or a widget, and build it in SvelteKit. Then compare the bundle and the code size with what you'd have written in React. That tells you more than any benchmark chart.

Svelte JavaScript Frontend SvelteKit Web Development Performance
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.