Svelte & SvelteKit (50 Qs)•Part 1: Basic & Foundational Concepts (Junior / Entry-Level)
How do `$effect()` and `$effect.pre()` handle side effects?
junior LevelCode ExampleSignalsSvelte 5
In Simple Words:
$effect(() => { ... }): Runs after the component has mounted and after any reactive dependencies read inside it change. Replaces Svelte 4's$: { ... }and React'suseEffect.- It automatically tracks any
$state()or$derived()signals accessed inside the function—no manual dependency arrays! - Can return a cleanup function.
- It automatically tracks any
$effect.pre(): Executes before the DOM is updated (useful for measuring scroll positions before layout changes).
svelte
<script>
let count = $state(0);
$effect(() => {
console.log(`The count is now ${count}`);
const timer = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(timer); // Cleanup on dependency change or unmount
});
</script>