Discover how lifecycle hooks save you from messy manual checks and hidden bugs!
Why lifecycle hooks run code at key moments in Svelte - The Real Reasons
Imagine you build a web app and want to run some code exactly when a component appears on the screen or just before it disappears.
You try to add code everywhere manually, checking if the component is visible or not.
Manually tracking when components mount or unmount is tricky and messy.
You might forget to clean up resources, causing bugs or slowdowns.
It's hard to keep your code organized and reliable.
Svelte lifecycle hooks let you run code automatically at key moments like when a component starts or stops.
This keeps your code clean, predictable, and easy to manage.
if(componentIsVisible) { startTimer(); } else { stopTimer(); }
import { onMount } from 'svelte'; onMount(() => { startTimer(); return () => stopTimer(); });
You can easily run setup and cleanup code exactly when needed, making your app more efficient and bug-free.
Starting a countdown timer when a popup opens and stopping it when the popup closes without extra checks.
Manual tracking of component states is error-prone and messy.
Lifecycle hooks run code automatically at important moments.
This leads to cleaner, safer, and more maintainable code.
Practice
Solution
Step 1: Understand lifecycle hooks
Lifecycle hooks are special functions that run at specific times in a component's life, like when it appears or disappears.Step 2: Identify their main role
The main role is to run code at these key moments, such as setup or cleanup tasks.Final Answer:
To run code at important moments during a component's life -> Option DQuick Check:
Lifecycle hooks = run code at key moments [OK]
- Thinking lifecycle hooks are for styling
- Confusing hooks with event handlers
- Believing hooks define props
Solution
Step 1: Recall lifecycle hook purposes
onMountruns code after the component appears on the page, perfect for setup tasks.Step 2: Match hook to timing
onDestroyruns when component is removed,beforeUpdateandafterUpdaterun around updates, not mounting.Final Answer:
onMount -> Option AQuick Check:
Code after component appears = onMount [OK]
- Using onDestroy for setup
- Confusing beforeUpdate with onMount
- Thinking afterUpdate runs on mount
import { onMount, onDestroy } from 'svelte';
let timer;
onMount(() => {
timer = setInterval(() => console.log('tick'), 1000);
});
onDestroy(() => {
clearInterval(timer);
});What happens when this component is removed from the page?
Solution
Step 1: Understand onMount and onDestroy usage
onMount starts a timer that logs 'tick' every second. onDestroy clears that timer when component is removed.Step 2: Predict behavior on removal
When removed, onDestroy runs and clears the timer, stopping the logs.Final Answer:
The timer stops and no more 'tick' logs appear -> Option CQuick Check:
onDestroy clears timer = stops logs [OK]
- Assuming timer runs forever
- Forgetting to clear timers causes memory leaks
- Thinking component reloads on removal
import { onMount } from 'svelte';
onMount(() => {
console.log('Mounted');
});
onMount(() => {
console.log('Setup');
});What is the problem here?
Solution
Step 1: Check multiple onMount usage
Svelte allows multipleonMountcalls; 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 BQuick Check:
Multiple onMount hooks run fine [OK]
- Thinking multiple hooks cause errors
- Believing only one hook runs
- Assuming onMount must be inside a function
Solution
Step 1: Identify when to start fetch
Fetching data should start when component appears, soonMountis the right hook.Step 2: Identify when to cancel fetch
If component is removed before fetch finishes,onDestroyruns to cancel or clean up the fetch.Final Answer:
Use onMount to start fetch and onDestroy to cancel it -> Option AQuick Check:
Start onMount, cancel onDestroy [OK]
- Using update hooks for fetch start/cancel
- Starting fetch onDestroy (too late)
- Canceling fetch onMount (too early)
Ready to prove it?
Pass the test and this pattern moves unknown
