Svelte Reactivity: The Compiler Instead of a Virtual DOM
Svelte compiles components at build time into targeted DOM code instead of diffing a virtual DOM at runtime. I show the mental model, reactive assignment with $: and the classic push trap that I keep running into in projects.
Two rules carry a large part of Svelte 3’s legacy model. First: the compiler recognizes assignments such as count += 1, obj.key = value or array[index] = value; a mere method call such as array.push(...) is not such an assignment. Second: a $: statement depends on the variables the compiler statically recognizes in its body. The direct syntax and some typical surprises follow from that.
Both rules come from the same source. Svelte decides while compiling a component which variable touches which DOM node. What arrives in the browser are finished update instructions; there is no tree comparison at runtime. So count += 1 really is enough – but only as long as you know how the compiler recognizes a change.
The basis is Svelte 3, the current major version in April 2022. Everything that follows is based on the assignment-based reactivity model and the $: declarations. This isn’t complete; it’s the slice that lets you grasp the mental model the fastest.
Editorial note (July 2026): For new code, Svelte 5 preferably works with runes such as $state, $derived and $effect. The $: and assignment model explained here belongs to the legacy mode, which is still supported. “Without a Virtual DOM” is still true, but on its own it no longer describes today’s reactivity API.
The mistake in thinking almost everyone brings along#
If you come from React, you carry a certain picture in your head: a component is a function that runs again on every state change and returns a description of the desired UI state – a virtual DOM tree. The framework compares this new tree with the old one, finds the differences and transfers only those to the real DOM. This diffing is clever, but it’s work that happens in the user’s browser on every update. Rich Harris put it sharply in his often-quoted text “Virtual DOM is pure overhead”: the virtual DOM is not a feature to be grateful for, but a means to an end – and a means with a price.
Svelte asks the question differently. If it’s already clear at build time which parts of the markup depend on which variables, why recompute this mapping in the browser on every update? The Svelte compiler analyzes the component statically and generates imperative JavaScript code that updates exactly the affected DOM nodes. No diff tree, no comparison at runtime. The compiler already knows that when count changes, exactly this one text node has to change, and it writes down exactly that instruction.
One clarification matters to me here, because it tends to blur in blog posts: Svelte is not “no runtime at all.” The compiled code brings along a small core of helper functions, on the order of a few kilobytes. What’s missing is the runtime diff algorithm and a heavyweight framework traveling along in the bundle. So the correct sentence is: no virtual DOM, no runtime diffing – not: zero runtime.
What the compiler takes over#
Before I get to the code, it’s worth looking at which tasks in Svelte are done by the compiler instead of by a runtime library. Exactly this shift explains why the whole thing means less overhead in the browser:
- The static analysis of which DOM node depends on which state variable – the result ends up as fixed code in the bundle, not as a computation at runtime.
- The generation of targeted update instructions that touch only the nodes actually affected, instead of comparing a complete tree.
- The resolution of
$:dependencies: the compiler determines from the source code which variables a reactive statement reads and generates the code for re-evaluation from that.
This last point is where most of the traps lie, and I devote most of what follows to it.
Reactivity through assignment#
Let’s look at the simplest reactive component. A file with the .svelte extension bundles script, markup and style. A completely normal let variable at the top level of the <script> block is already component state.
<script>
let count = 0;
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} times
</button>
There’s no special state API here. count is a variable, count += 1 is an assignment. The point on which everything hinges for me: it’s not the variable itself that is reactive; the assignment to it is the triggering event. The compiler has seen that count is referenced in the markup. So around every assignment, it generates the code that marks the component as “dirty” and rewrites the affected text node. What looks like an ordinary change of value is accompanied by a targeted update in the compiled result.
That also explains why some changes go nowhere. If you only read count or pass it around in a helper function, nothing is triggered. Only the assignment operator is the signal.
Derived values with $:#
The next building block is values that follow from other values. In React you reach for useMemo or compute in the render body. In Svelte 3 there is the reactive declaration with the $: label.
<script>
let count = 0;
$: doubled = count * 2;
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} times
</button>
<p>{count} * 2 = {doubled}</p>
$: doubled = count * 2; reads like a normal assignment with a strange prefix, but it’s an instruction to the compiler: “Keep doubled up to date as soon as one of its dependencies changes.” I don’t have to specify the dependencies myself. The compiler determines them at compile time from the source code – they are all variables that are read in the statement but not assigned. Here, that’s count. If count changes through an assignment, the declaration runs again, doubled gets a new value, and the dependent text node updates.
$: can do more than derived values. You can also use it to couple side effects to state changes:
<script>
let count = 0;
$: if (count >= 10) {
alert("count is dangerously high!");
}
$: console.log(`count is ${count}`);
</script>
Both forms run again as soon as count changes. The mechanism is the same as for the declaration: variables that are read become dependencies, assignments to them trigger re-evaluation. A detail for practice: these statements also run once during server-side rendering and before the first client render. They are part of the reactivity flow itself and not a replacement for a mount hook.
The following diagram shows this flow from the assignment to the DOM update – including the side path that later becomes the trap.
flowchart TD A[Assignment: count += 1] --> B[Variable marked as dirty] B --> C[reactive $: declarations<br/>re-evaluated] C --> D[targeted DOM update<br/>only affected nodes] E[array.push item] -.-> F[no assignment<br/>no reference change] F -.-> G[no update triggered]
Build time versus runtime#
The contrast with React becomes clear when you put both tracks side by side. Svelte determines dependencies and generates update code at build time; the browser still executes that code on every change. React creates a new element tree when rendering and reconciles it at runtime. So Svelte moves the analysis into the build, not all of the update work.
flowchart LR
subgraph Build[Build time – Svelte]
S1[.svelte component] --> S2[Svelte compiler]
S2 --> S3[targeted update code<br/>optimized vanilla JS]
end
subgraph Runtime[Runtime – React]
R1[Render function] --> R2[new virtual DOM tree]
R2 --> R3[Diff against old tree]
R3 --> R4[Patch to the real DOM]
endThe core of the picture is not “Svelte good, React bad,” but a different division of labor. React reconciles element trees at runtime. Svelte already knows the statically visible dependencies after the build and ships targeted update code for them. The user still runs this code, just not a virtual DOM diff for this update.
On bundle sizes, I deliberately stay cautious. The Svelte core is on the order of a few kilobytes, React plus ReactDOM considerably more. I give that as an order of magnitude, not as an exact measurement – the concrete numbers depend on the version, the bundler and what you actually use, and if you need a hard number, measure your own project.
The push trap#
Now to the flip side of the same model – the part this is really about for me. Because reactivity is tied to assignment, there is a class of changes that Svelte 3 simply doesn’t notice: in-place mutations without an assignment. The classic is Array.push.
<script>
let numbers = [1, 2, 3, 4];
function addBroken() {
numbers.push(numbers.length + 1);
}
</script>
<button on:click={addBroken}>Add number</button>
<p>{numbers.join(", ")}</p>
You click, the console confirms that the array grows – and nothing happens in the browser. No error, no warning, just no update. The reason follows consistently from the model: numbers.push(...) changes the existing array, but there is no assignment to numbers. Without an assignment, Svelte doesn’t mark the variable as dirty, and without the dirty mark, no update runs. The compiler can’t know that a method has touched the inside of the array – it only sees assignments.
The fix is as simple as the problem once you’ve internalized the model: you have to force an assignment. Two approaches are common.
<script>
let numbers = [1, 2, 3, 4];
function addWorking() {
numbers = [...numbers, numbers.length + 1];
}
function addAlsoWorking() {
numbers.push(numbers.length + 1);
numbers = numbers;
}
</script>
<button on:click={addWorking}>Add number</button>
<ul>
{#each numbers as n}
<li>{n}</li>
{/each}
</ul>
numbers = [...numbers, ...] creates a new array and assigns it – the clean variant familiar from other frameworks. numbers = numbers, on the other hand, looks like a no-op but is exactly what the compiler needs: an assignment to numbers that sets the dirty mark. So for Svelte to notice a change at all, the variable’s name has to end up on the left side of an =.
With objects, the situation differs from the method call: Svelte’s legacy compiler recognizes a direct assignment such as obj.key = value and updates dependent places. What stays invisible is a mutation that only happens inside a called function or method. Then you need an assignment visible to the compiler afterwards, or an immutable replacement via spread.
The quiet sibling: indirect dependencies#
There is a second trap that follows from the same principle and is less often recognized right away in reviews. The compiler determines the dependencies of a $: statement from which variables are directly referenced in the body. If you hide a variable behind a function call, it doesn’t appear in the body – and isn’t recognized as a dependency.
<script>
let count = 0;
function getCount() {
return count;
}
// count is not read directly here,
// so it is not a detected dependency
$: label = `value is ${getCount()}`;
</script>
label is computed on the first pass and never updated after that, because count isn’t visible in the body of the reactive declaration – only getCount() is there. The compiler has no way to recognize the dependency through the function boundary. The solution is to make the dependency visible, that is, to reference count directly in the statement. This isn’t a weakness; it’s the logical consequence of a model that analyzes statically at compile time instead of tracking dynamically at runtime.
What this means in practice#
If I pull these two traps together, I get a surprisingly compact mental model for Svelte 3 that boils down to two points:
- In legacy mode, reactivity is triggered by statically visible assignments. That includes direct property and index assignments, but not arbitrary method calls with internal mutations.
- Dependencies of
$:have to be directly visible in the body. Whatever disappears behind a function call isn’t tracked.
These two rules cover a large part of the surprises I run into in legacy Svelte projects. Both follow from the same design decision: dependencies are analyzed statically at build time. That calls for vigilance at function boundaries and with methods that mutate internally.
In a small data client, exactly these reactive assignments carry the data flow: a response replaces the previous value, and the compiler updates the dependent expressions in a targeted way.
Conclusion#
Svelte reverses a basic assumption of many frontend frameworks: instead of comparing a virtual DOM at runtime, it lets the compiler determine at build time which state touches which DOM node, and generates targeted update code from that. This eliminates this category of runtime diffing; how big the practical advantage is depends on the application and the update pattern. Everyday code stays pleasantly direct – count += 1 is enough. In legacy mode, reactivity hinges on statically visible assignments. Once you’ve internalized that, you understand both the push trap and indirect dependencies.
Further reading#
- Slide deck on this topic: https://slides.mikebild.dev/introduction-svelte.en.html
- Svelte Docs – the
$:syntax and the dependencies determined at compile time in the component format - Svelte Tutorial – the chapters on Reactivity, Assignments and Updating arrays and objects
- Virtual DOM is pure overhead – Rich Harris on the motivation behind the compiler approach
- Write less code – Svelte’s guiding principle of shipping less runtime code
Revised and translated from German with the help of AI.