All posts

Fix Memory Leak in Svelte

Fix memory leaks in Svelte applications caused by unsubscribed stores, lingering event listeners, and improper component cleanup.

Memory Leaks in Svelte

Svelte components are compiled to efficient JavaScript, but memory leaks can still occur through event listeners, store subscriptions, and third-party library integrations that aren't properly cleaned up.

Event Listeners Not Removed

Listeners added in onMount must be removed in the returned cleanup function:

<script>
  import { onMount } from 'svelte';

  onMount(() => {
    const handler = (e) => console.log(e);
    window.addEventListener('resize', handler);

    // CRITICAL: return cleanup function
    return () => {
      window.removeEventListener('resize', handler);
    };
  });
</script>

Manual Store Subscriptions

The $store syntax auto-unsubscribes, but manual subscribe() calls don't:

<script>
  import { onDestroy } from 'svelte';
  import { myStore } from './stores';

  // BAD — no unsubscribe
  myStore.subscribe(value => {
    doSomething(value);
  });

  // GOOD — capture and call unsubscribe
  const unsubscribe = myStore.subscribe(value => {
    doSomething(value);
  });
  onDestroy(unsubscribe);
</script>

Third-Party Libraries

Chart libraries, map widgets, and rich text editors allocate their own memory:

<script>
  import { onMount, onDestroy } from 'svelte';
  let chart;

  onMount(() => {
    chart = new Chart(canvas, config);
  });

  onDestroy(() => {
    chart?.destroy();
  });
</script>

Detecting Leaks

Use Chrome DevTools' Memory tab. Take heap snapshots before and after navigating between routes. Objects that survive navigation without reason are likely leaked.

Bugsly's browser integration tracks long-lived pages for memory growth, alerting your team to components that leak before users notice degraded performance.

Try Bugsly Free

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

Get Started Free