onMount lifecycle hook run in Svelte?onMount hook. When exactly does the code inside onMount execute?import { onMount } from 'svelte'; onMount(() => { console.log('Component is now in the DOM'); });
The onMount hook runs once right after the component is inserted into the DOM. This is useful for running code that depends on the component being visible, like fetching data or starting animations.
beforeUpdate runs?beforeUpdate lifecycle hook runs before the DOM updates. What is the state of component variables when beforeUpdate runs?import { beforeUpdate } from 'svelte'; let count = 0; beforeUpdate(() => { console.log(count); }); function increment() { count += 1; }
The beforeUpdate hook runs after state variables have changed but before the DOM updates. So the variables reflect the new values.
onDestroy code not run as expected?onDestroy never runs. What is the likely reason?import { onDestroy } from 'svelte'; let timer = setInterval(() => { console.log('tick'); }, 1000); // Missing onDestroy call // onDestroy(() => { // clearInterval(timer); // });
The cleanup code inside onDestroy is commented out, so it never runs. This means the timer keeps running even after the component is removed.
afterUpdate lifecycle hook?The afterUpdate hook is a function that takes a callback. Option B uses the correct syntax.
onMount, beforeUpdate, and onDestroy exist in Svelte.Lifecycle hooks let you run code at key moments in a component's life. This helps manage side effects like data fetching, DOM updates, or cleanup.
