In Svelte, a component's onMount lifecycle method is called after the first time the component has been rendered to the DOM. For example, if you have a component that is wrapped within an {# if} block, then when this block's conditional statement is fulfilled, the component will be mounted to the DOM, at which point onMount will be called. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that DOM elements within the component will be available for your code to access/manipulate.

Here's a template of how the onMount lifecycle method is used inside of a component:

Considered the most commonly used lifecycle method, onMount covers a wide diversity of use cases such as...

  • Accessing DOM elements.

  • Registering event listeners.

  • Fetching data from a remote API to lazy load components.

  • Loading embeddable widgets/plugins from third-party libraries.

Below, I'm going to show you:

  • The versatility of hooking into the mounting lifecycle phase.

  • Four demos that demonstrate practical use cases for onMount.

  • How to call onMount from an external module.

Use Case #1 - Accessing DOM Elements#

When you visit the G-Mail login page, you will notice that the e-mail address input field is automatically focused:

Focused E-Mail Address Input Field

This convenience automates away the initial click (or tabbing) into the input field that the user would have to do before being able to type in their e-mail address. Using the onMount lifecycle method, the focus can be moved to an input field when the component is initially rendered.

Visit this simple Svelte REPL demo to see how to automatically focus an input field using the onMount lifecycle method:

Demo - onMount Lifecycle Method - Login Form

Demo - `onMount` Lifecycle Method - Login Form

When you load the Svelte REPL, the e-mail address input field is automatically focused (indicated by its blue outline).

The bind:this directive sets the variable it's passed a reference to an element's DOM node. Here, the emailAddressInput variable is set to the <input type="email" /> element. Since onMount runs after the component has been rendered, the input field will exist by the time this method is executed. Therefore, emailAddressInput will have been set to this input field, and the focus can immediately be moved to it.

Note: Automatically focusing into an input field may skip over vital information a user using assistive technologies should be aware of. This may have negative implications on the accessibility of the application.

Use Case #2 - Fetching Data From a Remote API#

Lazy-loading content reduces the initial load time of an application and reduces bandwidth by delivering only what the client has requested. Imagine having to wait seconds or minutes for a large webpage containing tables with thousands or millions of rows to be downloaded before seeing any content in your browser. Before the webpage finishes downloading, you would have most likely moved on to a different webpage. Wouldn't it be better if you were presented some content immediately (to keep you engaged), and then be shown a "loading" message when you request to view a large table?

The onMount lifecycle method can be used to retrieve data from a remote API. This data can then be set to a variable in your component, which will cause the component to only re-render the part of the DOM that's affected by changes to this variable. This is especially useful for lazy-loading a table that contains many records.

Visit this simple Svelte REPL demo to see how to fetch motor vehicle collisions data from the NYC Open Data API and render this data as rows of cells in a table using the onMount lifecycle method:

Demo - onMount Lifecycle Method - NYC Open Data API

Demo - `onMount` Lifecycle Method - NYC Open Data API

Here, we are fetching data from the NYC Open Data Portal, particularly on NYC motor vehicle collisions. Each record of this dataset features the location of the accident, the vehicles involved, the number of fatalities, etc.

For fetching data, we are using the native fetch method. The fetch method returns a Promise, so we will schedule an async callback to run when the component is mounted.

While the data is being fetched, a "Loading..." message is presented to the user to notify them of the table's status (initially, isLoading is set to true, and this flag toggles this message on/off). Once the data is downloaded and parsed, the collisions variable is set to this data and the isLoading flag is set to false. As a result, the "Loading..." message disappears, and a select number of features of each record are displayed in the table.

Note: Alternatively, this can be accomplished with an {#await } block! Note: Since onMount is not ran during server-side rendering, if you need to fetch data within a component after its initial rendering, then it must be done within onMount and not outside at the top-level of <script />.Note: Since async functions always return a Promise, onMount cannot return an unmount function since it must synchronously return a value.

Use Case #3 - Registering Event Listeners#

Event listeners execute code when an event, such as moving the mouse, takes place on the element it's binded to. In component-based applications, event listeners are registered once the component has been rendered to the page.

Visit this simple Svelte REPL demo to see how to add an event listener on the window "resize" event using the onMount lifecycle method:

Demo - onMount Lifecycle Method - Window Resize

Demo - `onMount` Lifecycle Method - Window Resize

As you resize the browser window, notice how the window width displayed in the view changes. Just before the component is unmounted from the DOM, the unmount callback returned from onMount will be executed. This will remove this event listener from window, which will avoid memory leaks in legacy browsers, such as Internet Explorer, that do not automatically garbage-collect event handlers of removed DOM elements.

Use Case #4 - Loading Embeddable Widgets/Plugins From Third-Party Libraries#

When embedding a widget/plugin from a third-party library, those libraries will need to know where to place the widget/plugin in your application. For example, to display Google Maps via Google's Maps JavaScript API, the first argument to the google.maps.Map method is a reference to an existing DOM element (often document.getElementById('map')) on the page where you wish to place the map.

Visit this simple Svelte REPL demo to see how to embed a Leaflet map into your Svelte application using the onMount lifecycle method:

Demo - onMount Lifecycle Method - Leaflet Map

Demo - `onMount` Lifecycle Method - Leaflet Map

The <svelte:head /> element inserts elements into the <head /> element of the document. In this context, we are adding the Leaflet CSS and JavaScript files. By using <svelte:head />, it keeps all Leaflet-related code encapsulated within a single component that contains all code related to rendering the Leaflet map. When the component is mounted, the <div id="map" /> container element will exist when the onMount callback is executed. The Leaflet library will be able to find this element and initialize the map.

Note: This can also be done with Google Maps, but this example uses Leaflet since the Google Maps API requires an API key. To generate this API key, you must provide Google with your billing information in their Google Cloud Platform, and I felt this would add more an unnecessary obstacle to learning how load an embeddable widget/plugin with onMount.Note: If the Leaflet map is toggled on/off, then return an unmount callback that runs map.remove() to destroy the map and clear all of its related event listeners.

Calling onMount From an External Module#

Let's take the focus input example and refactor it. Instead of having the onMount code (and its contents) in the same file as the component, let's move it into an external module.

Demo - onMount - External Module

(onMount.js)

(App.svelte)

Notice how the bind:this directive was removed from the e-mail address input field. This is because the reference of the DOM node captured by this directive cannot be passed as an argument to the onMountFocusInput method. The DOM node reference will not be available when this method is executed since it is called at the top-level of the <script /> tag. Instead, we can pass an id value so that onMount can query for the input field element once the component that contains it is rendered.

Additionally, by moving this onMount code outside of the component, it can be reused for other components that may need to automatically focus an input field when they are rendered to the page.

Next Steps#

If you have built React applications, then you will have probably noticed how similar onMount is to componentDidMount/useEffect. Try rewriting some of the those components that use componentDidMount/useEffect as Svelte components that use onMount.

If you want to learn more about Svelte, then check out Fullstack Svelte:

Sources#