Performance: Lifecycle in nested components
This affects the initial page load speed and interaction responsiveness by controlling when nested components run their setup and teardown code.
/* In a nested Svelte component */ onMount(() => { // Defer heavy work asynchronously setTimeout(() => { // heavy task runs after initial render }, 0); });
/* In a nested Svelte component */ onMount(() => { // Heavy synchronous task like large data processing for (let i = 0; i < 1_000_000; i++) { // simulate work } });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous work in nested onMount | Multiple nested nodes mounted | Multiple reflows if layout changes | High paint cost due to delayed rendering | [X] Bad |
| Deferred heavy work after mount | Same DOM operations | Single reflow during mount | Lower paint cost, faster interaction | [OK] Good |
onMount runs after the component is rendered.onMount is the first lifecycle method called after the component is inserted, before any updates or destruction.onMount in a nested Svelte component?import { onMount } from 'svelte'; using named import from 'svelte'.onMount(() => { ... }) registers the callback properly. Assigning onMount to a function is incorrect.onMount hooks that log messages. What is the order of console logs when the parent is rendered?onMount runs first.onMount logs first, then parent's onMount logs after child is fully mounted.onDestroy hook, but it never runs when the component is removed. What is the most likely cause?onDestroy only runs when the component is removed. If it stays in DOM, it won't run.onDestroy incorrectly or mixing hooks causes errors, but the main reason is component not unmounting.onMount and cleans up a subscription in onDestroy. If the parent conditionally renders this child multiple times, what is the best practice to avoid memory leaks?onDestroy must clean up resources each time to prevent leaks.onDestroy ensures no leftover subscriptions remain after unmount.Pass the test and this pattern moves unknown