New Sep 18, 2024

Breaking out of Svelte's reactive statements

More Front-end Bloggers All from Zell Liew View Breaking out of Svelte's reactive statements on zellwk.com

(Hey, we're having problems showing images in RSS right now, so if you want a better reading experience, consider viewing this article online [here](https://zellwk.com//blog/svelte-reactive-statements-breakout. We hope to fix this soon!).

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).

Scroll to top