Lifecycle hooks let you run code exactly when your component starts, updates, or ends. This helps you control what happens at important times.
When you want to fetch data right after a component appears on the screen.
When you need to clean up timers or event listeners before a component disappears.
When you want to react to changes in component data or props.
When you want to set up animations when a component is created.
When you want to log or track component behavior during its life.
Syntax
Svelte
import { onMount, beforeUpdate, afterUpdate, onDestroy } from'svelte';
onMount(() => {
// code to run when component is added to the page
});
beforeUpdate(() => {
// code to run before the component updates
});
afterUpdate(() => {
// code to run after the component updates
});
onDestroy(() => {
// code to run when the component is removed
});
Each hook runs at a specific time in the component's life.
A. Only the first onMount runs, the second is ignored
B. Both onMount hooks run correctly without error
C. Multiple onMount hooks cause a syntax error
D. onMount must be inside a component function
Solution
Step 1: Check multiple onMount usage
Svelte allows multiple onMount calls; all run in order when component mounts.
Step 2: Confirm no syntax or scope errors
Both hooks run and log messages; no syntax error or ignoring occurs.
Final Answer:
Both onMount hooks run correctly without error -> Option B
Quick Check:
Multiple onMount hooks run fine [OK]
Hint: Multiple onMount hooks run in order, no error [OK]
Common Mistakes:
Thinking multiple hooks cause errors
Believing only one hook runs
Assuming onMount must be inside a function
5. You want to fetch data when a Svelte component appears and cancel the fetch if the component is removed before it finishes. Which lifecycle hooks should you use and why?
hard
A. Use onMount to start fetch and onDestroy to cancel it
B. Use beforeUpdate to start fetch and afterUpdate to cancel it
C. Use onDestroy to start fetch and onMount to cancel it
D. Use afterUpdate to start fetch and beforeUpdate to cancel it
Solution
Step 1: Identify when to start fetch
Fetching data should start when component appears, so onMount is the right hook.
Step 2: Identify when to cancel fetch
If component is removed before fetch finishes, onDestroy runs to cancel or clean up the fetch.
Final Answer:
Use onMount to start fetch and onDestroy to cancel it -> Option A
Quick Check:
Start onMount, cancel onDestroy [OK]
Hint: Start fetch onMount, cancel onDestroy for cleanup [OK]
Common Mistakes:
Using update hooks for fetch start/cancel
Starting fetch onDestroy (too late)
Canceling fetch onMount (too early)
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.