Handling Lifecycle Effects with onMount and onDestroy

Introduction to Lifecycle Effects in Svelte

In the previous lesson, you learned how to create reusable code blocks using snippets in Svelte. This allowed you to build modular and scalable components by defining reusable templates and rendering them dynamically. Now, we’ll shift our focus to another essential aspect of Svelte: lifecycle effects.

Lifecycle effects are actions that occur at specific stages of a component’s existence, such as when it is first rendered or when it is removed from the DOM. Managing these effects is crucial for tasks like fetching data, setting up event listeners, and cleaning up resources to avoid memory leaks. In Svelte, lifecycle effects are handled using two key functions: onMount and onDestroy.

In this lesson, you’ll learn how to use onMount to perform actions when a component is first rendered and onDestroy to clean up resources when a component is removed from the DOM. By the end of this lesson, you’ll be able to manage lifecycle effects effectively in your Svelte applications.

Using `onMount` for Initialization

The onMount function is used to perform actions when a component is first rendered. This is particularly useful for tasks like fetching data from an API or setting up event listeners. Let’s look at an example where we fetch user data when the component is mounted.

Here’s how you can use onMount to fetch user data:

<script>
  import { onMount } from 'svelte';

  let user = $state(null);
  let isLoading = $state(true);
  let error = $state(null);

  onMount(async () => {
    try {
      const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      user = await response.json();
    } catch (err) {
      error = err.message;
    } finally {
      isLoading = false;
    }
  });
</script>

{#if isLoading}
  <p>Loading user data...</p>
{:else if error}
  <p>Error: {error}</p>
{:else if user}
  <h2>{user.name}</h2>
  <p>Email: {user.email}</p>
  <p>Phone: {user.phone}</p>
{/if}

In this example:

  • We import onMount from Svelte and define reactive state variables using $state.
  • Inside onMount, we fetch user data from an API. If the fetch is successful, we store the user data in the user variable. If there’s an error, we store the error message in the error variable.
  • Finally, we set isLoading to false to indicate that the data fetching is complete.

The component renders a loading message while the data is being fetched, an error message if something goes wrong, and the user’s details once the data is successfully fetched.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal