0
0
Svelteframework~30 mins

Lifecycle in nested components in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Lifecycle in nested components
📖 Scenario: You are building a simple Svelte app with a parent component and a nested child component. You want to see how lifecycle functions work in both components.
🎯 Goal: Create a parent component and a nested child component. Use Svelte lifecycle functions onMount and onDestroy in both components to log messages when they mount and unmount.
📋 What You'll Learn
Create a Svelte component called Child.svelte with onMount and onDestroy lifecycle functions that log messages.
Create a Svelte component called Parent.svelte that imports Child.svelte and uses it inside its markup.
Add onMount and onDestroy lifecycle functions in Parent.svelte that log messages.
Render Child inside Parent so you can observe lifecycle logs for both.
💡 Why This Matters
🌍 Real World
Understanding lifecycle in nested components helps you build interactive apps where components mount and unmount dynamically, such as tabs, modals, or lists.
💼 Career
Many frontend jobs require knowledge of component lifecycles to manage resources, fetch data, and clean up properly in frameworks like Svelte.
Progress0 / 4 steps
1
Create the Child component with lifecycle logs
Create a Svelte component file named Child.svelte. Inside it, import onMount and onDestroy from svelte. Use onMount to log the message "Child mounted" and onDestroy to log "Child destroyed". Add a simple <p> tag with the text "I am the child component".
Svelte
Hint

Remember to import onMount and onDestroy from svelte and use them as functions inside the <script> tag.

2
Create the Parent component with lifecycle logs
Create a Svelte component file named Parent.svelte. Import onMount and onDestroy from svelte. Use onMount to log the message "Parent mounted" and onDestroy to log "Parent destroyed". Add a simple <h1> tag with the text "I am the parent component".
Svelte
Hint

Use the same lifecycle functions as in the child, but with messages for the parent.

3
Import and use Child component inside Parent
In Parent.svelte, import the Child component from ./Child.svelte. Add the <Child /> tag below the <h1> tag to render the child component inside the parent.
Svelte
Hint

Use import Child from './Child.svelte' and add <Child /> in the markup.

4
Complete the app by exporting Parent as default
In Parent.svelte, add export default for the component by ensuring the file is saved as a Svelte component. No extra code is needed, just confirm the file exports the component by default.
Svelte
Hint

Just save the file as Parent.svelte. Svelte automatically exports the component.