0
0
Svelteframework~5 mins

Lifecycle in nested components in Svelte

Choose your learning style9 modes available
Introduction

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.

When you want to run code when a child component appears or disappears.
When you need to fetch data or start timers inside a nested component.
When you want to clean up resources like event listeners in nested parts.
When you want to track when nested components mount or update.
When you want to coordinate actions between parent and child components.
Syntax
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.

Examples
This runs code when the child component first appears on the page.
Svelte
import { onMount } from 'svelte';

onMount(() => {
  console.log('Child component mounted');
});
This runs cleanup code when the child component is removed from the page.
Svelte
import { onDestroy } from 'svelte';

onDestroy(() => {
  console.log('Child component removed');
});
These run code before and after the child component updates its content.
Svelte
import { beforeUpdate, afterUpdate } from 'svelte';

beforeUpdate(() => {
  console.log('Child will update soon');
});

afterUpdate(() => {
  console.log('Child updated');
});
Sample Program

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.

Svelte
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>
OutputSuccess
Important Notes

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.

Summary

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.