In Svelte, a component's onDestroy lifecycle method is called before the component is removed from the DOM. For example, if you have a component that is wrapped within an {#if} block and it is currently rendered to the DOM, then when this block's conditional statement evaluates to false, the component will be unmounted from the DOM, at which point onDestroy will be called. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that cleanup-related operations can be ran and previous application states can be resumed.

Here's a template of how the onDestroy lifecycle method is used inside of a component:

Compared to the function returned from onMount, there are specific reasons for using onDestroy:

As a vital lifecycle method, onDestroy covers a wide diversity of use cases such as...

  • Resuming previous application states such as returning focus back to the main content of the webpage when a modal dialog is closed.

  • Unregistering event listeners.

  • Scheduling store unsubscriptions.

  • Caching removed elements or fetched data.

  • Performing "clean-up duties" for external/third-party libraries.

Below, I'm going to show you:

  • The versatility of hooking into the unmounting lifecycle phase.

  • Five demos that demonstrate practical use cases for onDestroy.

  • How different onDestroy is compared to the function returned from onMount.

  • How to call onDestroy in a server-side rendering application.

Use-Case #1 - Returning Focus to Element That Opened Modal Dialog#

When a modal dialog is closed, the focus should return back to the element that opened the modal dialog. Not doing so would hurt the experience of users who rely on keyboards and/or assistive technologies to navigate through webpages. To rescue the focus:

  1. Set a variable (previouslyFocused) at the top-level of the modal component's <script /> block to a reference of the previously focused element (for example, a button that toggles the modal dialog).

  2. Before the modal is unmounted from the DOM (closing the modal via clicking a "Close Modal" button, clicking outside of the modal dialog or pressing the ESC key), inside of onDestroy, return the focus back to the previously focused element referenced by the previouslyFocused variable.

Visit this simple Svelte REPL demo to see how to refocus a previous element using the onDestroy lifecycle method:

Demo - onDestroy Lifecycle Method - Modal

Demo - `onDestroy` Lifecycle Method - Modal

(Modal.svelte)

When the "Open Modal" button is clicked, it sets the isModalOpened flag to true, which causes the <Modal /> component to be rendered to the page. When an instance of the <Modal /> component is created, its <script /> block is executed, and previouslyFocused is set to document.activeElement, which references the most-recently focused element (the "Open Modal" button).

Notice that the "Close Modal" button in the modal dialog is focused due to its autofocus attribute. When you click the "Tab" key, the focus is trapped within the modal dialog (each press moves the focus to each link, followed by the "Close Modal" button, and back, repeating in a cycle), which prevents the focus from escaping the modal dialog.

When you press the "ESC" key or click the "Close Modal" button, then the "close" event is dispatched, which will execute the closeModal function, set the isModalOpened flag to false and remove the modal dialog from the DOM. Before the modal dialog is unmounted, the callback passed to onDestroy will be ran. The focus will resume back to the previously focused element, the "Open Modal" button.

Note: In Firefox and Safari, document.activeElement references the <body /> element in an <iframe /> element (where the Svelte REPL displays the result of the Svelte code). In the demo, a reference to the "Open Modal" button is passed to the <Modal /> component as a prop, and it is manually used as the previously focused element if document.activeElement references the <body /> element.

Use-Case #2 - Removing Event Listeners#

Removing event listeners is necessary for avoiding memory leaks in older browsers that don't automatically garbage-collect event handlers of removed DOM elements. A common pattern for registering and unregistering event listeners in Svelte is to perform these actions during the onMount and onDestroy lifecycle methods respectively.

Visit this simple Svelte REPL demo to see how to remove event listeners in your Svelte application using the onDestroy lifecycle method:

Demo - onDestroy Lifecycle Method - Removing Event Listeners (Window Resize)

Demo - `onDestroy` Lifecycle Method - Removing Event Listeners (Window Resize)

(WindowResize.svelte)

Resizing the window updates the printed width value. By debouncing the event handler, the resize event listener will only call the event handler after the resize event has stopped firing for 300ms. Limiting the rate at which the event handler is executed will yield performance gains, especially in much larger applications.

To trigger the onDestroy lifecycle method, press the "Toggle" button to toggle off the <WindowResize /> component. This will remove the registered resize event listener on the window object. If, instead, the event listener was binded to an element within the component, then the event listener can be binded to the element in onMount since the element will have been rendered by the time onMount is called. Likewise, the event listener can be removed from the element in onDestroy since onDestroy occurs just before the element is removed from the DOM, which means the element still exists when removing this event listener.

Use-Case #3 - Logging User Activity#

To understand how a UI change can affect a user's engagement with your application, you might collect a set of metrics, such as bounce rate and average session duration, via Google Analytics or software custom-built to log this information. A simple metric to integrate into your application is tracking how long a user stays on a page. A rudimentary implementation of this would involve starting a timer the moment the user visits the page, and then stopping the timer the moment they exit the page.

Visit this simple Svelte REPL demo to see how to log user activity in your Svelte application using the onDestroy lifecycle method:

onDestroy Lifecycle Method - Logging User Activity

`onDestroy` Lifecycle Method - Logging User Activity

(RedditArticle.svelte)

In this example, each tab represents a "subreddit," a topic-specific, online community on Reddit (r/science, r/technology and r/worldnews). Clicking on any of these tabs will display a list containing the most popular articles for the corresponding subreddit.

The <RedditArticles /> component is mounted anytime the user clicks on any of the subreddit tabs. Upon switching from one subreddit to another, the current <RedditArticles /> component will be unmounted, and a new <RedditArticles /> component will be mounted. The subreddit prop is passed to ensure the articles for the currently selected subreddit are loaded.

When an instance of the <RedditArticles /> component is created, this represents the user landing on a new "page," and a timer begins to mark this (let startTime = performance.now();). Once the user leaves the "page" (switching to a new subreddit), the onDestroy lifecycle method is called, and the difference between the time at which the component is unmounted and the recorded start time is calculated. This difference represents how long the user was on this subreddit before leaving. After performing this calculating, the difference can be sent to an API endpoint to be stored. All of the data collected can then be aggregated and viewed inside of a dashboard.

Use-Case #4 - Scheduling Store Unsubscriptions#

Typically, in component-based architectures, data flows downwards from parents to children (unidirectional). In Svelte, stores allow data to be shared between components, regardless of their relationship in the component hierarchy. A store contains a subscribe method that notifies components of changes to the store's value. When the subscribe method is executed, an unsubcribe method is returned, which cancels a component's subscription to a store when called.

Visit this simple Svelte REPL demo to see how to unsubscribe from a Svelte store subscription using the onDestroy lifecycle method:

onDestroy Lifecycle Method - Scheduling Store Unsubscriptions

`onDestroy` Lifecycle Method - Scheduling Store Unsubscriptions

(RedditArticles.svelte)

In this example, the "Logging User Activity" demo has been repurposed with the <Subreddits /> component (the tabs) and the <RedditArticles /> component (the list of subreddit articles) both subscribed to a store named reddit.

(store.js)

currentSubreddit represents the currently selected subreddit (by default, it is r/science). Because the value of currentSubreddit can be modified, this store is a writable store, which means two additional methods are provided alongside the subscribe method: set (sets a new value for the store and synchronously executes every active subcription method of the store) and update (updates a value based on the current value in the store). For convenience, a custom method, setCurrentSubreddit, is made available, and it directly updates the currentSubreddit value. All components subscribed to the store will see the changes. In this case, both the <App /> and <RedditArticles /> components are subscribed to the store for changes to currentSubreddit.

Imagine a scenario in which a component is mounted/unmounted many times throughout the lifetime of the application. If unsubscribe is not called upon unmounting the component, then its corresponding subscription will still be alive and will be executed upon future updates to the store even when the component the subscription is tied to has been unmounted. Try this out by commenting out the unsubscribe function call in the <RedditArticles /> component's onDestroy and adding a console.log() statement inside of the subscription function. As you switch tabs from one subreddit to another, watch as more and more messages are printed inside of the console.

Svelte Store Subscriptions - Without `unsubscribe`

With so many subscriptions still in memory and not garbage-collected, eventually, this will cause a memory leak.

To avoid this situation, the unsubscribe method must be called inside of onDestroy lifecycle method.

Note: Subscribing to the store and adding a call to the unsubscribe method inside of many components that rely on the store can become tedious and resemble repetitive boilerplate code. Instead, just import the store and prefix a store value with a $ to auto-subscribe to it. The auto-subscription shorthand will allow components to auto-subscribe to the store and automatically unsubscribe from it when the component is destroyed. Check out the <Subreddits /> component for an auto-subscription example.

(Subreddits.svelte)

Use-Case #5 - Performing "Clean-Up Duties" for External/Third-Party Libraries#

For third-party libraries such as Leaflet.js that embed interactive maps into an application, the provide methods for "cleaning-up" when they are removed from the DOM. For example, in the case of Leaflet.js, the remove method destroys the map and its layers and clears all of their corresponding event listeners.

Visit this simple Svelte REPL demo to see how to clean-up an embedded Leaflet map in your Svelte application using the onDestroy lifecycle method:

onDestroy Lifecycle Method - Clean-Up External/Third-Party Libraries

`onDestroy` Lifecycle Method - Clean-Up External/Third-Party Libraries

(LeafletMap.svelte)

When the map is toggled on, the <LeafletMap /> component's onMount lifecycle method is called and initializes a new map on a specified container element. Additionally, a marker icon is displayed, and an event listener is added to this icon. Whenever the icon is clicked, a popup opens above it. Once the map is toggled off, the <LeafletMap /> component's onDestroy lifecycle method is called and destroys the map and the marker and clears all of their corresponding event listeners such as zooming in the map, the opening of the marker icon's popup on clicking, etc.

Server-Side Rendering#

When server-side rendering a Svelte application, only one lifecycle method is called: onDestroy. Particularly, onDestroy is called after the application is rendered.

For example, when building the static version of a Sapper application via npm run export, only onDestroy is called. To verify this, simply add a console.log statement into each lifecycle method call and observe the outputted logs in the CLI.

(src/routes/index.svelte)

Sapper - SSR

Next Steps#

If you have built React applications, then you will have probably noticed how similar onDestroy is to componentWillUnmount. Try rewriting some of those components that use componentWillUnmount as Svelte components that use onDestroy.

If you want to learn more about Svelte, then check out Fullstack Svelte:

Sources#