Performance: onMount
onMount affects the timing of when JavaScript code runs after the component is added to the page, impacting initial interaction readiness and rendering speed.
import { onMount } from 'svelte'; onMount(() => { setTimeout(() => { // heavy code deferred for (let i = 0; i < 100000000; i++) {} }, 0); });
import { onMount } from 'svelte'; onMount(() => { // heavy synchronous code for (let i = 0; i < 100000000; i++) {} });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous code in onMount | 1 (component mount) | 1 reflow triggered | Blocks paint until done | [X] Bad |
| Light or deferred code in onMount | 1 (component mount) | 1 reflow triggered | Paint happens promptly | [OK] Good |
onMount in a Svelte component?onMountonMount is a lifecycle function in Svelte that runs after the component is added to the page.onMount purposeonMount.onMount in a Svelte component?onMount is a named export, so it must be imported with curly braces: import { onMount } from 'svelte';onMountonMount(() => { /* code */ });. Assigning it like a variable is incorrect.import { onMount } from 'svelte';
let count = 0;
onMount(() => {
count = 5;
console.log(count);
});
console.log(count);console.log(count) runs immediately, before onMount callback runs, so it logs 0.onMount, count is set to 5 and logged, so the second log is 5.onMount:import { onMount } from 'svelte';
onMount = () => {
console.log('Mounted');
};onMount instead of calling onMount() with a callback.onMount(() => { console.log('Mounted'); }); to register the callback properly.onMount?onMount runs once after component appears, perfect for fetching data and starting timers.onMount. Use onMount to fetch data and start timer but do not return cleanup misses cleanup, so it's incomplete.onMount to fetch data and return a cleanup function to clear the timer correctly fetches data and returns cleanup function to clear timer, which is best practice.Pass the test and this pattern moves unknown