Trusted answers to developer questions

What is OnMount() in Svelte?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Svelte is a JavaScript framework used to develop web applications. It is unique because it runs the application on compile, and compiles the code in Vanilla JavaScript.

Component render

Componentsform a single webpage are a concept that come from a popular framework named React. Suppose a single web page is divided into three components:

  1. Search bar
  2. Submit button
  3. Queries section

OnMount is a function that is called when a component is initialized. In other words, we can say that when a component renders, the first function it calls is onMount. This is similar to the concept of calling useEffect in React with an empty array as a parameter.

Syntax

The following piece of code explains the syntax of onMount function.

<script>
import { onMount } from 'svelte';
let array = [];
onMount(async () => {
const res = await fetch(`https://jsonplaceholder.typicode.com/photos?_limit=20`);
array = await res.json();
});
</script>

RELATED TAGS

javascript
framework
webapplication
Did you find this helpful?