8 Lifecycle functions

 

This chapters covers

  • onMount to run code when a component is added to the DOM
  • beforeUpdate to run code before every component update
  • afterUpdate to run code after every component update
  • onDestroy to run code when a component is removed from the DOM

In some applications there are actions that need to be performed when a component is added to or removed from the DOM. There are also situations where actions need to be performed before or after a component is updated. Svelte supports this by allowing the registration of functions to be invoked when four specific events occur in the lifecycle of a component instance:

  • When it is mounted (added to the DOM)
  • Before it is updated
  • After it is updated
  • When it is destroyed (removed from the DOM)

A component is “updated” if any of its props change or any of its state variables change. Recall that state variables are top-level variables in a component that are used in its HTML.

8.1 Setup

To register functions for these events, import the provided lifecycle functions from the svelte package:

import {afterUpdate, beforeUpdate, onDestroy, onMount} from 'svelte';

Call these functions, passing them a function to be called when the event occurs. They must be called during component initialization. This means they cannot be called conditionally or be called in a function that is not invoked before each component instance is mounted.

8.2 The onMount lifecycle function

 
 

8.2.1 Moving focus

 
 

8.2.2 Retrieving data from an API service

 
 

8.3 The onDestroy lifecycle function

 
 

8.4 The beforeUpdate lifecycle function

 
 
 

8.5 The afterUpdate lifecycle function

 
 
 
 

8.6 Using helper functions

 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest