0
0
Svelteframework~15 mins

Why lifecycle hooks run code at key moments in Svelte - See It in Action

Choose your learning style9 modes available
Why lifecycle hooks run code at key moments
📖 Scenario: You are building a simple Svelte component that shows a message when it appears on the screen and cleans up when it disappears. This helps understand how lifecycle hooks let you run code at important times.
🎯 Goal: Create a Svelte component that uses lifecycle hooks onMount and onDestroy to show messages in the console when the component loads and unloads.
📋 What You'll Learn
Create a Svelte component with a message variable
Use onMount lifecycle hook to set the message to 'Component is mounted!'
Use onDestroy lifecycle hook to set the message to 'Component is destroyed!'
Display the message in the component's HTML
💡 Why This Matters
🌍 Real World
Lifecycle hooks help run code at important times like loading data when a page opens or cleaning up timers when a page closes.
💼 Career
Understanding lifecycle hooks is key for building interactive web apps that respond correctly to user actions and system events.
Progress0 / 4 steps
1
Set up the message variable
Create a Svelte component with a let variable called message initialized to an empty string ''.
Svelte
Hint

Use let message = '' to create a variable that can change later.

2
Import and use onMount lifecycle hook
Import onMount from 'svelte' and use it to set message to 'Component is mounted!' inside the onMount callback function.
Svelte
Hint

Use import { onMount } from 'svelte' and then onMount(() => { message = 'Component is mounted!' }).

3
Import and use onDestroy lifecycle hook
Import onDestroy from 'svelte' and use it to set message to 'Component is destroyed!' inside the onDestroy callback function.
Svelte
Hint

Use import { onDestroy } from 'svelte' and then onDestroy(() => { message = 'Component is destroyed!' }).

4
Display the message in the component
Add an HTML <p> tag that shows the {message} variable inside the Svelte component.
Svelte
Hint

Use <p>{message}</p> to show the message in the page.