What is onDestroy() method in Svelte JavaScript?

What is Svelte?

Svelte is a JavaScript framework used to develop web applications. It is unique because it runs the application on compile and compiles the code in Vanilla JavaScript.

What is onDestroy()?

The onDestroy() method is a function that we can use to decide if a component or an HTMLHyperText Markup Language page is unrendered or unmountedkilled or becomes useless. It then dictates what action should be performed using this function.

The onDestroy() method in Svelte is similar to ComponentWillUnMount() in React framework.

onDestroy() and lifecycle of Svelte

The onDestroy() function is part of the Svelte lifecycle that contains functions such as:

  • onMount()
  • onDestroy()
  • beforeUpdate and afterUpdate
  • tick

To understand individual components working, refer to the official documentation .

Code

Suppose we want to clear localStorage when a particular component is killed or becomes useless. We call localStorage clear function in the onDestroy() of that component.

<script>
import { onDestroy } from 'svelte';
onDestroy(() => localStorage.clear()); //clears local storage
</script>
<div>
<p>
Welcome to Educative component. This component will call onDestroy when its killed.
</p>
</div>

Free Resources