0
0
Svelteframework~30 mins

beforeUpdate and afterUpdate in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using beforeUpdate and afterUpdate in Svelte
📖 Scenario: You are building a simple Svelte component that tracks a counter. You want to run some code right before the counter updates and right after it updates, to see how these lifecycle functions work.
🎯 Goal: Create a Svelte component with a counter variable. Use beforeUpdate to log a message before the counter changes, and afterUpdate to log a message after the counter changes. Add a button to increase the counter.
📋 What You'll Learn
Create a count variable initialized to 0
Use beforeUpdate to run a function that logs 'Before update: count is {count}'
Use afterUpdate to run a function that logs 'After update: count is {count}'
Add a button that increments count by 1 when clicked
💡 Why This Matters
🌍 Real World
Using lifecycle functions like beforeUpdate and afterUpdate helps manage side effects and synchronize UI updates in interactive web apps.
💼 Career
Understanding Svelte lifecycle functions is important for frontend developers building reactive and performant user interfaces.
Progress0 / 4 steps
1
Set up the counter variable
Create a let variable called count and set it to 0 inside the <script> tag.
Svelte
Hint

Use let count = 0; inside the <script> tag.

2
Add beforeUpdate lifecycle function
Import beforeUpdate from 'svelte' and use it to run a function that logs `Before update: count is ${count}` before the component updates.
Svelte
Hint

Use beforeUpdate(() => { console.log(`Before update: count is ${count}`); });

3
Add afterUpdate lifecycle function
Import afterUpdate from 'svelte' and use it to run a function that logs `After update: count is ${count}` after the component updates.
Svelte
Hint

Use afterUpdate(() => { console.log(`After update: count is ${count}`); });

4
Add button to increment count
Add an on:click event to the <button> that increases count by 1 when clicked.
Svelte
Hint

Add on:click={() => count += 1} to the <button> tag.