All posts

Fix Infinite Loop in Svelte

Fix infinite reactive loops in Svelte caused by reactive statements triggering their own dependencies and improper store subscriptions.

Reactive Loops in Svelte

Svelte's reactivity model is compile-time magic, but it can bite you when a reactive statement modifies a variable it depends on. The browser tab locks up, and you're stuck.

The Problem

A $: reactive block that writes to a variable it reads:

<script>
  let count = 0;

  // INFINITE LOOP — reads and writes count
  $: count = count + 1;
</script>

Svelte detects the change to count, reruns the reactive block, which changes count again, and so on.

The Fix

Separate the trigger from the output. Use a derived value or introduce a distinct variable:

<script>
  let clicks = 0;
  $: doubled = clicks * 2;

  function increment() {
    clicks += 1;
  }
</script>

<button on:click={increment}>
  Clicks: {clicks}, Doubled: {doubled}
</button>

Store Subscription Loops

Another common pattern is a store subscription that writes back to the same store:

<script>
  import { myStore } from './stores';
  // BAD — subscribing and setting in the same reaction
  $: $myStore = transform($myStore);
</script>

Instead, react to a different signal or use beforeUpdate with a guard:

<script>
  import { myStore, triggerStore } from './stores';
  $: if ($triggerStore) {
    $myStore = transform($myStore);
  }
</script>

Monitoring tools like Bugsly won't catch client-side freezes as exceptions per se, but they will detect the resulting unresponsiveness and user-reported errors that follow.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free