0
0
Svelteframework~10 mins

Why lifecycle hooks run code at key moments in Svelte - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to run a function when the component is first added to the page.

Svelte
import { onMount } from 'svelte';

onMount(() => {
  console.log([1]);
});
Drag options to blanks, or click blank then click option'
A'Component loaded!'
BComponent loaded!
ConMount
Dconsole.log('Component loaded!')
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the message string.
Trying to call onMount inside itself.
2fill in blank
medium

Complete the code to clean up when the component is removed from the page.

Svelte
import { onDestroy } from 'svelte';

onDestroy(() => {
  [1];
});
Drag options to blanks, or click blank then click option'
Aconsole.log(Cleaning up!)
Bconsole.log('Cleaning up!')
ConDestroy()
Dcleanup()
Attempts:
3 left
💡 Hint
Common Mistakes
Missing quotes around the message.
Calling onDestroy inside itself.
3fill in blank
hard

Fix the error in the code to run code after the component updates.

Svelte
import { afterUpdate } from 'svelte';

afterUpdate(() => {
  console.log([1]);
});
Drag options to blanks, or click blank then click option'
Aconsole.log('Component updated')
BComponent updated
CafterUpdate
D'Component updated'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string without quotes causes an error.
Trying to call afterUpdate inside itself.
4fill in blank
hard

Fill both blanks to run code when the component mounts and cleans up when it is destroyed.

Svelte
import { [1], [2] } from 'svelte';

[1](() => {
  console.log('Mounted');
});

[2](() => {
  console.log('Destroyed');
});
Drag options to blanks, or click blank then click option'
AonMount
BonDestroy
CafterUpdate
DbeforeUpdate
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up onMount and onDestroy.
Using update hooks instead of mount/destroy hooks.
5fill in blank
hard

Fill all three blanks to log messages at mount, update, and destroy lifecycle moments.

Svelte
import { [1], [2], [3] } from 'svelte';

[1](() => {
  console.log('Mounted');
});

[2](() => {
  console.log('Updated');
});

[3](() => {
  console.log('Destroyed');
});
Drag options to blanks, or click blank then click option'
AonMount
BafterUpdate
ConDestroy
DbeforeUpdate
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing beforeUpdate with afterUpdate.
Forgetting to import all three hooks.