What are Svelte lifecycle functions?
Answer
Svelte provides lifecycle functions for component initialization, updates, and cleanup. Import from svelte: onMount: runs after the component is first rendered to the DOM. The primary place for setup code requiring DOM access, API calls, and subscriptions. Return a cleanup function to run on destroy. onDestroy: runs when the component is removed from the DOM. Clean up subscriptions, timers, and event listeners. beforeUpdate: runs before the DOM updates. Access the current (pre-update) DOM state. afterUpdate: runs after the DOM updates — access the updated DOM. Example: import { onMount, onDestroy } from 'svelte'; onMount(() => { const timer = setInterval(() => count++, 1000); return () => clearInterval(timer); }). Lifecycle functions must be called during component initialization (synchronously in the script), not conditionally or asynchronously.