0
0
SvelteHow-ToBeginner · 3 min read

How to Use onMount in Svelte: Simple Guide with Examples

In Svelte, use the onMount function to run code after the component appears in the page. Import onMount from 'svelte' and pass it a function that runs your setup code. This is useful for fetching data or starting timers when the component loads.
📐

Syntax

The onMount function is imported from 'svelte' and takes a callback function that runs once when the component is first added to the DOM.

The callback can return a cleanup function that runs when the component is removed.

svelte
import { onMount } from 'svelte';

onMount(() => {
  // code to run after component mounts
  return () => {
    // optional cleanup code when component unmounts
  };
});
💻

Example

This example shows how to use onMount to fetch data when the component loads and display it.

svelte
<script>
  import { onMount } from 'svelte';
  let message = 'Loading...';

  onMount(async () => {
    const response = await fetch('https://api.chucknorris.io/jokes/random');
    const data = await response.json();
    message = data.value;
  });
</script>

<main>
  <h1>Random Joke</h1>
  <p>{message}</p>
</main>
Output
Random Joke <p>Chuck Norris joke text fetched from API</p>
⚠️

Common Pitfalls

  • Not importing onMount from 'svelte' causes errors.
  • Running code outside onMount that depends on the DOM may fail because the component isn't mounted yet.
  • Forgetting to return a cleanup function when setting intervals or subscriptions can cause memory leaks.
svelte
/* Wrong: missing import and no cleanup */

onMount(() => {
  const id = setInterval(() => console.log('tick'), 1000);
});

/* Right: import and cleanup */

import { onMount } from 'svelte';

onMount(() => {
  const id = setInterval(() => console.log('tick'), 1000);
  return () => clearInterval(id);
});
📊

Quick Reference

onMount runs code after the component is added to the page.

Use it to start timers, fetch data, or interact with the DOM safely.

Return a function to clean up when the component is removed.

Key Takeaways

Import onMount from 'svelte' to run code after component mounts.
Use onMount for setup tasks like fetching data or starting timers.
Return a cleanup function inside onMount to avoid memory leaks.
Avoid running DOM-dependent code outside onMount to prevent errors.
onMount runs only once when the component is first added to the DOM.