0
0
Svelteframework~5 mins

onMount in Svelte

Choose your learning style9 modes available
Introduction

The onMount function runs code right after a Svelte component appears on the screen. It helps you start tasks like loading data or setting up timers.

You want to fetch data from a server when a page or component loads.
You need to start a timer or animation when a component shows up.
You want to focus an input box automatically after the component appears.
You need to set up event listeners that depend on the component being visible.
Syntax
Svelte
import { onMount } from 'svelte';

onMount(() => {
  // code to run after component appears
  return () => {
    // optional cleanup code when component is removed
  };
});

The function inside onMount runs once after the component is added to the page.

You can return a cleanup function to run when the component is removed.

Examples
This logs a message once when the component appears.
Svelte
import { onMount } from 'svelte';

onMount(() => {
  console.log('Component is now visible');
});
This starts a timer when the component appears and stops it when the component is removed.
Svelte
import { onMount } from 'svelte';

let time;
onMount(() => {
  time = setInterval(() => {
    console.log('Tick');
  }, 1000);

  return () => clearInterval(time);
});
This fetches user data once the component loads and updates the name variable.
Svelte
import { onMount } from 'svelte';

let name = '';
onMount(async () => {
  const response = await fetch('https://api.example.com/user');
  const data = await response.json();
  name = data.name;
});
Sample Program

This component shows "Loading..." first. After 1 second, onMount changes the message to "Hello from onMount!".

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

  onMount(() => {
    setTimeout(() => {
      message = 'Hello from onMount!';
    }, 1000);
  });
</script>

<main>
  <p>{message}</p>
</main>
OutputSuccess
Important Notes

onMount only runs in the browser, not during server-side rendering.

Use onMount for setup tasks that need the component to be visible.

Summary

onMount runs code after a component appears on the page.

It is useful for fetching data, starting timers, or focusing elements.

You can clean up resources by returning a function inside onMount.