Challenge - 5 Problems
Lifecycle Mastery in Svelte
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
When does the
onMount lifecycle hook run in Svelte?Consider a Svelte component using the
onMount hook. When exactly does the code inside onMount execute?Svelte
import { onMount } from 'svelte'; onMount(() => { console.log('Component is now in the DOM'); });
Attempts:
2 left
💡 Hint
Think about when you want to run code that needs the component to be visible on the page.
✗ Incorrect
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.
❓ state_output
intermediate2:00remaining
What happens to state when
beforeUpdate runs?In Svelte, the
beforeUpdate lifecycle hook runs before the DOM updates. What is the state of component variables when beforeUpdate runs?Svelte
import { beforeUpdate } from 'svelte'; let count = 0; beforeUpdate(() => { console.log(count); }); function increment() { count += 1; }
Attempts:
2 left
💡 Hint
Think about when you want to check the new state before the screen changes.
✗ Incorrect
The beforeUpdate hook runs after state variables have changed but before the DOM updates. So the variables reflect the new values.
🔧 Debug
advanced2:00remaining
Why does this
onDestroy code not run as expected?A developer wants to clean up a timer when a Svelte component is removed. But the cleanup code inside
onDestroy never runs. What is the likely reason?Svelte
import { onDestroy } from 'svelte'; let timer = setInterval(() => { console.log('tick'); }, 1000); // Missing onDestroy call // onDestroy(() => { // clearInterval(timer); // });
Attempts:
2 left
💡 Hint
Check if the cleanup code is actually active in the component.
✗ Incorrect
The cleanup code inside onDestroy is commented out, so it never runs. This means the timer keeps running even after the component is removed.
📝 Syntax
advanced2:00remaining
Which option correctly uses the
afterUpdate lifecycle hook?Select the code snippet that correctly runs code after the component updates the DOM in Svelte.
Attempts:
2 left
💡 Hint
Remember how to call lifecycle hooks as functions with callbacks.
✗ Incorrect
The afterUpdate hook is a function that takes a callback. Option B uses the correct syntax.
🧠 Conceptual
expert3:00remaining
Why are lifecycle hooks important in Svelte components?
Choose the best explanation for why lifecycle hooks like
onMount, beforeUpdate, and onDestroy exist in Svelte.Attempts:
2 left
💡 Hint
Think about what tasks happen when a component appears, changes, or disappears.
✗ Incorrect
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.