tezvyn:

Svelte's Reactivity: A Compiler, Not a Library

AI-drafted, machine-checkedSource: developer.mozilla.orgintermediate
Svelte's Reactivity: A Compiler, Not a Library

Svelte achieves reactivity at compile time, not runtime. It's a compiler that turns your component files into efficient, imperative JavaScript that updates the DOM directly, skipping the virtual DOM. The footgun: reactivity only triggers on assignment.

WHY IT EXISTS: Traditional frameworks use a virtual DOM (VDOM) at runtime. When state changes, they create a new VDOM, compare it to the old one, and apply the differences to the real DOM. This "diffing" process adds overhead. Svelte was created to eliminate this runtime work by moving it to compile time.

THE MENTAL MODEL: Think of Svelte as a "disappearing framework." It's not a library you include in your browser bundle; it's a compiler that processes your component files during your build step. It takes your declarative code and compiles it into small, efficient, imperative JavaScript that directly manipulates the DOM.

HOW IT WORKS: Svelte's reactivity is triggered by the assignment operator (=). When the Svelte compiler sees a variable declaration and a later assignment to it (like count += 1), it instruments that assignment. The compiled JavaScript will not just update the variable; it will also include the precise code needed to update any part of the DOM that depends on it. This is how it achieves surgical updates without a VDOM.

WHEN TO USE IT: Svelte is excellent for projects where performance and small bundle size are critical, such as interactive visualizations, embedded widgets, or mobile-first web apps. Its low boilerplate and simple state management make it a strong choice for small to medium-sized applications.

WHEN NOT TO USE IT: The assignment-based reactivity can be a pitfall. If you have complex, nested state objects that are frequently mutated, you might find the need for constant reassignment cumbersome. For example, updating a deep property requires recreating the object path. This can be less ergonomic than the proxy-based reactivity of other frameworks for very large applications.

ONE CANONICAL EXAMPLE: To update an array and have the UI react, you must reassign it. This will NOT trigger a UI update: myArray.push(newItem);. This WILL trigger an update: myArray = [...myArray, newItem];. The second example works because the assignment signals to the Svelte compiler that the variable has changed and the DOM may need updating.

Read the original → developer.mozilla.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.