Lifecycle methods help you run code at specific times in a component's life. In nested components, they let each part do its own setup and cleanup.
Lifecycle in nested components in Svelte
import { onMount, beforeUpdate, afterUpdate, onDestroy } from 'svelte'; onMount(() => { // code to run when component mounts }); beforeUpdate(() => { // code before component updates }); afterUpdate(() => { // code after component updates }); onDestroy(() => { // code when component is removed });
Each lifecycle function runs only inside the component where it is declared.
Nested components have their own lifecycle independent from their parents.
import { onMount } from 'svelte'; onMount(() => { console.log('Child component mounted'); });
import { onDestroy } from 'svelte'; onDestroy(() => { console.log('Child component removed'); });
import { beforeUpdate, afterUpdate } from 'svelte'; beforeUpdate(() => { console.log('Child will update soon'); }); afterUpdate(() => { console.log('Child updated'); });
This example shows a parent component that includes a child component. Both have onMount and onDestroy lifecycle functions that log messages. When the parent and child appear or disappear, their own lifecycle code runs separately.
Parent.svelte: <script> import Child from './Child.svelte'; import { onMount, onDestroy } from 'svelte'; onMount(() => { console.log('Parent mounted'); }); onDestroy(() => { console.log('Parent destroyed'); }); </script> <Child /> Child.svelte: <script> import { onMount, onDestroy } from 'svelte'; onMount(() => { console.log('Child mounted'); }); onDestroy(() => { console.log('Child destroyed'); }); </script> <p>This is the child component content.</p>
Lifecycle functions in nested components run independently and in order of mounting.
When a parent is removed, its children are removed too, triggering their onDestroy functions.
Use console logs or DevTools to see lifecycle events in action.
Each nested component has its own lifecycle methods.
Use onMount and onDestroy to run setup and cleanup code.
Lifecycle methods help manage resources and actions in nested parts of your app.