How to

What Are They and How Do They Work?


Key Takeaways

  • Svelte’s lifecycle hooks allow you to control the different stages of a component’s lifecycle, such as initialization, updating, and destruction.
  • The four major lifecycle hooks in Svelte are onMount, onDestroy, beforeUpdate, and afterUpdate.
  • By utilizing these lifecycle hooks, you can perform actions like fetching data, setting up event listeners, cleaning up resources, and updating the UI based on state changes.


Svelte is a modern JavaScript framework that lets you build efficient web applications. One of Svelte’s critical features is its lifecycle hooks which provide you with control over the different stages of a component’s lifecycle.


What Are Lifecycle Hooks?

Lifecycle hooks are methods that trigger at specific points in the lifecycle of a component. They allow you to perform particular actions at these points, such as initializing the component, responding to changes, or cleaning up resources.

Different frameworks have different lifecycle hooks, but they all share some common features. Svelte offers four major lifecycle hooks: onMount, onDestroy, beforeUpdate, and afterUpdate.

Setting Up a Svelte Project

To understand how you can use Svelte’s lifecycle hooks, start by creating a Svelte project. You can do this in various ways, such as using Vite (a front-end build tool) or degit. Degit is a command-line tool to download and clone git repositories without downloading the entire git history.

Using Vite

To create a Svelte project using Vite, run the following command in your terminal:

 npm init vite

Once you run the command, you will answer some prompts to provide your project’s name, the framework you want to use, and the specific variant of that framework.

Now, navigate to the project’s directory and install the necessary dependencies.

Run the following commands to do this:

 cd svelte-app
npm install

Using degit

To set up your Svelte project using degit, run this command in your terminal:

 npx degit sveltejs/template svelte-app

Then, navigate to the project’s directory and install the necessary dependencies:

 cd svelte-app
npm install

Working With the onMount Hook

The onMount hook is a vital lifecycle hook in Svelte. Svelte calls the onMount hook when a component is first rendered and inserted into the DOM. It is similar to the componentDidMount lifecycle method in React class components or the useEffect hook in React functional components with an empty dependency array.

You will primarily use the onMount hook to perform initialization tasks, such as fetching data from an API or setting up event listeners. The onMount hook is a function that takes a single argument. This argument is the function that the application will call when it first renders the component.

Here is an example of how you can use the onMount hook:

 <script>
import { onMount } from 'svelte'
onMount( () => { console.log('Component has been added to the DOM')} );
</script>

<div>
    <p>This is a random component</p>
</div>

In your svelte-app project, create a src/Test.svelte file and add the above code to it. This code imports the onMount hook from Svelte and calls it to run a simple function that logs text on the console. To test the onMount hook, render the Test component in your src/App.svelte file:

For example:

 <script>
import Test from "./Test.svelte";
</script>

<main>
    <h1>Hello There!</h1>
    <Test />
</main>

Then run the app:

 npm run dev

Running this command will provide you with a local URL like http://localhost:8080. Visit the link in a web browser to view your application. The app will log the text “Component has been added to the DOM” in your browser’s console.

Working With the onDestroy Hook

As the opposite of the onMount hook, Svelte calls the onDestroy hook when it is about to remove a component from the DOM. The onDestroy hook is useful for cleaning up any resources or event listeners you set up during the component’s lifecycle.

This hook is similar to React’s componentWillUnmount lifecycle method and its useEffect hook with a cleanup function.

Here is an example of how to use the onDestroy hook:

 <script>
import { onDestroy } from "svelte";
let intervalId;

intervalId = setInterval(() => {
  console.log("interval");
}, 1000);

onDestroy(() => {
  clearInterval(intervalId);
});
</script>

This code starts a timer that logs the text “interval” to your browser’s console every second. It uses the onDestroy hook to clear the interval when the component leaves the DOM. This prevents the interval from continuing to run when the component is no longer needed.

Working With the beforeUpdate and afterUpdate Hooks

The beforeUpdate and afterUpdate hooks are lifecycle functions that run before and after the DOM undergoes an update. These hooks are useful for performing actions based on state changes, such as updating the UI or triggering side effects.

The beforeUpdate hook runs before the DOM updates and anytime the component’s state changes. It is similar to getSnapshotBeforeUpdate in React class components. You mainly use the beforeUpdate hook when comparing the application’s new state to its old state.

Below is an example of how to use the beforeUpdate hook:

 <script>
import { beforeUpdate } from "svelte";

let count = 0;

beforeUpdate(() => {
  console.log("Count before update:", count);
});

function increment() {
  count += 1;
}
</script>

<button on:click={increment}>Count: {count}</button>

Replace the code in your Test component with the code block above. This code uses the beforeUpdate hook to log the value of the count state before the DOM updates. Each time you click the button, the increment function runs and increases the value of the count state by 1. This causes the beforeUpdate function to run and log the value of the count state.

The afterUpdate hook runs after the DOM updates. It is generally used for running code that needs to happen after the DOM updates. This hook is similar to componentDidUpdate in React. The afterUpdate hook works like the beforeUpdate hook.

For example:

 <script>
import { afterUpdate } from "svelte";

let count = 0;

afterUpdate(() => {
  console.log("Count after update:", count);
});

function increment() {
  count += 1;
}
</script>

<button on:click={increment}>Count: {count}</button>

The code block above is similar to the previous one, but this one uses the afterUpdate hook to log the value of the count state instead. This means it will log the count state after the DOM updates.

Build Robust Apps Using Svelte’s Lifecycle Hooks

The lifecycle hooks in Svelte are essential tools used to create dynamic and responsive applications. Understanding lifecycle hooks is a valuable part of Svelte programming. Using these hooks, you can control the initialization, update, and destruction of your components, and handle their state changes.

Leave a Reply

Your email address will not be published. Required fields are marked *