How Svelte onMount works

If you’re coming from a React or even an Angular world , you’re use to fetching initial data or updating React state on the componentDidMount lifecycle.

So, what does this look like in Svelte?

Svelte has the mechanism as React. Every Svelte component goes through a phase of lifecycles, and onMount is one of those lifecycles.

What is Svelte onMount

This lifecycle comes right after the initial render of a Svelte component.

  import { onMount } from 'svelte';

  onMount(() => {
    // ... Run something after component has mounted
    console.log('App component has mounted');


Within a <script> tag you must import the onMount function from the svelte package.


onMount accepts a callback function. This callback function gets executed once the component has mounted on to the application.

The output should look something like this.

App component has mounted

When to use Svelte onMount?

That’s actually a great question.

Data fetching

Just like React componentDidMount, this is a great place to data fetch lazily.

  import { onMount } from 'svelte';

  // Array of photos
  let photos = [];

  onMount(async () => {
    const res = await fetch(``);
    // Update state variable, photos
    photos = [...await res.json()];

The callback function for onMount supports async/await.

This comes in handy when you’re doing SSR applications with Svelte.

Do we need to use Svelte onMount hook

If you ever pay close attention to your Svelte component. It never re-renders the entire component like React does.

  let number = 0;

  const handleClick = () => number += 1;


  <button on:click="{handleClick}">Increment</button>

  main {
    text-align: center;
    padding: 1em;
    max-width: 750px;
    margin: 0 auto;

  h1 {
    color: purple;
    font-family: 'Comic Sans MS', cursive;
    font-size: 2em;
    display: block;
    text-align: center;

Updating the number variable will not cause the Svelte component to re-run like how it would happen within a React render() method.

So, console.log('render') will only trigger once.

So this begs to question.

Do we even need to use the onMount()?

According to the creator, Rich Harris, no but you should for good habit practice.

And it seems to be good practice if Svelte ever decides to bring in a React Suspense API style into Svelte.

I like to tweet about Svelte and post helpful code snippets. Follow me there if you would like some too!