#svelte #javascript #frontend

Day 8: Lifecycle & Effects

Welcome to Day 8. Svelte 5 simplifies the lifecycle heavily relying on one rune: $effect.

The $effect Rune

Runs immediately, and re-runs whenever any state inside it changes.

<script>
  let count = $state(0);

  $effect(() => {
    console.log(`The count is now ${count}`);
    
    // Cleanup function (runs before re-running or unmounting)
    return () => {
      console.log('Cleaning up...');
    };
  });
</script>

This replaces afterUpdate and most uses of onMount.

onMount

Still exists! Use it for one-off setup logic that only runs in the browser (not SSR).

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

  onMount(() => {
    // Canvas setup, 3rd party libs
    console.log('Mounted');
  });
</script>

$effect.pre

Need to update the DOM before the browser paints? Use $effect.pre. Handy for keeping scroll positions.

Challenge for Day 8

  1. Create a Timer component.
  2. Use $effect to set an interval that increments count.
  3. Ensure you return a cleanup function to clearInterval!
  4. Toggle the component with an {#if} block to prove it cleans up (check the console).

Solution:

<script lang="ts">
  let count = $state(0);

  $effect(() => {
    const interval = setInterval(() => {
      count++;
    }, 1000);

    return () => clearInterval(interval);
  });
</script>

<h1>Seconds: {count}</h1>

Simple and robust. Tomorrow, we add some flair with Styles & Transitions.