ZL
About Articles Contact
Published on Sep 18, 2024
Filed under:
#svelte

Breaking out of Svelte's reactive statements

If you use Svelte, you may notice that Svelte lets you create reactive statements with $. It kinda looks like this:

let count = 0
$: double = count * 2

In this case, double will change automatically to count * 2 whenever count changes. This is an excellent pattern that I love — so much that I figured out how to do this in Vanilla JavaScript

The problem with this pattern, is you will face an error if you tried to handle DOM related tasks in an SSR environment.

// ERROR
$: {
const hello = document.querySelector('.world')
}

This error happens because the DOM is not available in an SSR environment. It is only available in client environments.

Solving the problem is simple. You can just break out of the reactive statement when the DOM is not ready.

$: {
if (typeof window === 'undefined') break $
// Your DOM related tasks here
}

That’s it! Have fun using the reactive pattern until Svelte 5 rolls around! (We may have to use a different syntax at that point).

Previous Clarifying the Relationship Between Popovers and Dialogs Next Forcing the future

Join My Newsletter

I share what I’m learning on this newsletter: code, building businesses, and living well.

Sometimes I write about technical deep-dives, product updates, musings on how to live, and sometimes my struggles and how I’m breaking through.

Regardless of the type of content, I do my best to send you an update every week.

If you’re into making things and growing as a person, you’ll probably feel at home here.

“

Zell is the rare sort of developer who both knows his stuff and can explain even the most technical jargon in approachable — and even fun — ways!

I’ve taken his courses and always look forward to his writing because I know I’ll walk away with something that makes me a better front-ender.

Geoff Graham
Geoff Graham — Chief Editor @ CSS Tricks
The Footer

General

Home About Contact Testimonials Tools I Use

Projects

Magical Dev School Splendid Labz

Socials

Youtube Instagram Tiktok Github Bluesky X

Follow Along

Email RSS
© 2013 - 2025 Zell Liew / All rights reserved / Terms