Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 35 ยท Quality

Debugging and Performance in Svelte

Debug Svelte 5 with $inspect, $inspect.trace, {@debug} and devtools, then speed up apps with keyed each blocks, $derived, $state.raw, lazy loading and bundle checks.

Two skills separate comfortable Svelte developers from frustrated ones: finding out why something updated (or did not), and keeping apps fast as they grow. Svelte 5's fine-grained reactivity gives you a head start on the second, and a few runes and tools cover the first.

The compiler is not available on this site, so Svelte code is read-only. The <TryIt> blocks re-create the ideas in plain JavaScript: a logging proxy that behaves like $inspect, a dependency tracer and a small benchmark.

$inspect: watch values change

$inspect(...) logs its arguments now and again whenever they change, deeply for objects and arrays. It exists only in development; the compiler removes it from production builds.

HTML
<script>
  let count = $state(0);
  let user = $state({ name: 'Ada', tags: ['math'] });

  $inspect(count, user);   // logs: init 0 {name: 'Ada', ...}, then update ...
</script>

<button onclick={() => count++}>{count}</button>
<button onclick={() => user.tags.push('code')}>add tag</button>

Customize the output with .with: its first argument is 'init' or 'update':

JavaScript
$inspect(count).with((type, value) => {
  if (type === 'update') debugger;   // break exactly when it changes
});

$inspect.trace() goes further. Put it as the first line of an $effect or $derived.by and Svelte logs which reactive value caused it to re-run. Perfect for "why does this effect keep firing?":

JavaScript
$effect(() => {
  $inspect.trace('search effect');
  fetchResults(query, page);
});

How $inspect sees deep changes

A $state object is a proxy: reading and writing go through traps, which is how Svelte (and this stand-in) know exactly what changed:

JS A deep-logging proxy, like $inspect

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This is also why you should not destructure $state values you want to stay reactive, and why console.log(user) shows a Proxy in devtools. Use $state.snapshot(user) to get a plain copy for logging or to pass to APIs such as structuredClone and postMessage:

JavaScript
console.log($state.snapshot(user));

{@debug} in markup

{@debug user, count} in a template logs those values and pauses at a debugger statement whenever any of them changes, if the devtools are open. It is a quick tool for template-level issues and is also dev-only:

HTML
{@debug user, count}
<h1>{user.name}</h1>

Browser tools

  • Svelte DevTools browser extension: inspect the component tree, props and state.
  • Source maps are on by default in dev, so the Sources panel shows your .svelte files and breakpoints work in them.
  • Network panel and ?debug logs help with SvelteKit data loading; the terminal prints server load errors.
  • svelte-check (run npx svelte-check) reports type errors and warnings across the project.

Common reactivity bugs

Symptom Likely cause Fix
UI does not update Value was reassigned from a plain let (no $state) declare with $state
Destructured value is stale let { a } = obj copies the value read obj.a, or use $derived
Effect runs forever It writes to state it also reads use $derived, or untrack the read
Class field not reactive Plain field in a class use $state fields in the class
state_unsafe_mutation error Changing state inside $derived or the template derived values must be pure

Performance basics

Svelte compiles templates into code that updates only what changed, so most apps are fast without effort. When one is not, check these in order.

1. Derive, do not sync

An $effect that copies one state into another causes an extra render pass. A $derived computes lazily and caches:

JavaScript
// slower and bug-prone
let filtered = $state([]);
$effect(() => { filtered = items.filter((i) => i.name.includes(query)); });

// better
let filtered = $derived(items.filter((i) => i.name.includes(query)));

2. Key your lists

{#each items as item (item.id)} lets Svelte move existing DOM nodes instead of rewriting them when the list changes, and preserves per-item state.

3. Avoid deep proxies for big data

$state wraps objects and arrays in proxies recursively. For a large read-only list (thousands of rows from an API) that you only ever replace wholesale, use $state.raw, which makes only reassignment reactive and avoids the proxy cost:

JavaScript
let rows = $state.raw([]);
rows = await loadRows();            // reactive: whole-value assignment
// rows.push(x) would NOT trigger an update with $state.raw

4. Do less work per update

  • Move expensive computing into $derived (cached until its dependencies change).
  • Debounce input handlers that call the network.
  • Virtualize very long lists (render only visible rows) with a small windowing helper or a library.
  • Prefer CSS transitions for hover effects and animate transform/opacity, not layout properties.

5. Ship less JavaScript

  • Import only what you need: import { debounce } from 'lodash-es', not the whole library.
  • Lazy-load heavy components with dynamic import() and render them when needed:
HTML
<script>
  let Chart = $state(null);
  async function showChart() {
    Chart = (await import('$lib/Chart.svelte')).default;
  }
</script>

<button onclick={showChart}>Show chart</button>
{#if Chart}<Chart data={rows} />{/if}
  • In SvelteKit, prerender what you can, and use csr = false for pages that need no interactivity (see Rendering Modes).
  • Analyze the bundle with rollup-plugin-visualizer or vite-bundle-visualizer to find large dependencies.

Measuring: derived caching versus recomputing

Measure before you optimize. This benchmark compares a recomputed filter with a cached one that only recalculates when its input changes, which is what $derived does:

JS Why derived caching matters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $inspect.trace() tell you inside an $effect?

    trace logs the dependencies that triggered the re-run, which is the fastest way to find an effect that fires too often.
  2. 2. How do you get a plain, non-proxy copy of a $state object?

    $state.snapshot returns a plain deep copy, useful for logging or passing to APIs that cannot handle proxies.
  3. 3. When is $state.raw a good choice?

    $state.raw skips deep proxying; only reassigning the variable triggers updates.
  4. 4. Why is $derived usually better than an $effect that sets another state?

    Derived values recompute only when their dependencies change and do not cause an additional reactive cycle.

Summary

  • $inspect (with .with and .trace), {@debug} and $state.snapshot are the debugging toolkit; all are development-only.
  • Most reactivity bugs come from non-$state variables, destructuring, or effects that write what they read.
  • For speed: use $derived, key {#each} blocks, $state.raw for big data and lazy-load heavy components.
  • Measure with devtools and a bundle visualizer before optimizing.

Next: TypeScript in Svelte