Component Lifecycle

Lifecycle Methods in Svelte

Svelte provides several lifecycle methods that allow you to run code at specific times during a component's existence.

Component Status

  • Mounted at:
  • Update count: 0
  • Timer (seconds): 0

Open the browser console (F12) to see lifecycle method logs.

onMount

The onMount function runs after the component is first rendered to the DOM. This is the ideal place to fetch data, set up timers, or add event listeners.

onDestroy

The onDestroy function runs when the component is removed from the DOM. This is where you should clean up any resources that might continue running.

beforeUpdate and afterUpdate

These functions run before and after the DOM is updated as a result of state changes.

Next Steps

Now that you understand component lifecycle, check out: