Lädt...

🔧 Understanding Svelte Component Lifecycle and Reactivity


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Svelte's component system features a specific approach to reactivity and component initialization. This article explores a common misconception about how props, variables, and component initialization work in Svelte.

The Misconception

Developers new to Svelte might assume that when a prop changes, the entire component script runs again, like if the component was a function and the prop a parameter: if the prop changes, the function will give another result, right?
This isn't how Svelte operates, and understanding this distinction is important for building functional applications.

Analyzing the Example

The example demonstrates this concept with two components:

  1. app.svelte: A parent component with buttons to select different names
  2. name.svelte: A child component that receives a name prop and tracks modifications

The Parent Component (app.svelte)

<script>
    // This shows that changing the prop does not rerun the component
    // script.

    import InputName from "./name.svelte";
    let names = ["John", "Mila", "Ali"];    
    let selected = $state();
</script>

<!-- This selector trigger the prop change in child component -->
{#each names as name}
    <button onclick={() => selected=name}>{name}</button>
{/each}

<!-- This section call the child component with the prop -->
{#if selected}
    <InputName name={selected}/>
{/if}

The parent component:

  • Maintains a list of names and a selected name state
  • Renders buttons for each name that update the selected variable
  • Also renders the InputName component with the selected name

The Child Component (name.svelte)

<script>
    // This is a simple component that implements change detection

    let { name } = $props();

    // this is executed only once at component mount
    let original = name;

    let changed = $derived(original != name);
</script>

Name : <input type="text" bind:value={name}>

{#if changed}
    modified
{/if}

The child component:

  • Receives a name prop using $props()
  • Stores the initial value in an original variable
  • Uses $derived to create a reactive changed variable that compares current and original values
  • Displays "modified" when the input value differs from the original

The Problem

When we click on a name and start updating the field, it shows the 'modified' indicator. This appears to work correctly.

However, when we click on another name, the indicator remains visible. We can also trigger this issue by clicking on the first name without modifying it, then clicking a second name: the 'modified' indicator appears despite not updating anything.

The key insight is that the component's script block runs only once when the component is initially mounted. When props change, Svelte updates the reactive dependencies without re-running the entire script.

This means that let original = name; is executed only once during component initialization. When the name prop changes later:

  1. The name value updates
  2. The changed derived value recalculates
  3. But the variable original still holds the first value it received

The Solution

To force the child component to re-execute its script when the name prop changes, we use a {#key} block in the parent component.

The {#key var} block triggers at var updates by destroying and recreating the components it surrounds.

For our example, we need to modify our code like this:

<!-- This section call the child component with the prop -->
{#if selected}
    {#key selected}
        <InputName name={selected}/>
    {/key}
{/if}

When selected changes:

  • Without {#key}, the same component instance would remain and the variable original would never update
  • With {#key}, Svelte destroys and recreates the InputName component, causing the script to run again and the variable original to be reset

Conclusion

  1. Be aware of one-time initialization: Variables assigned directly in the script block are initialized only once.
  2. Use reactive declarations: Leverage $derived for values that need to react to prop changes.
  3. Understand when to use {#key}: Use it when you need to completely reset a component state, like in our example for change detection patterns.
...

🔧 Understanding Svelte Component Lifecycle and Reactivity


📈 61.31 Punkte
🔧 Programmierung

🔧 From Svelte 4 to Svelte 5: Understanding Slots (default and named)


📈 36.46 Punkte
🔧 Programmierung

🔧 Understanding Svelte: Setting Up Your Project and Mastering .svelte Files


📈 36.46 Punkte
🔧 Programmierung

🔧 From Svelte 4 to Svelte 5: Understanding Slots (default and named)


📈 36.46 Punkte
🔧 Programmierung

🔧 How Reactivity in Vue and Svelte are different?


📈 35.85 Punkte
🔧 Programmierung

🔧 Svelte Reactivity: Let's Talk About $Effects


📈 34.71 Punkte
🔧 Programmierung

🔧 Learning the new Svelte v5 Reactivity System


📈 34.71 Punkte
🔧 Programmierung

🔧 Vue.js Lifecycle Hooks: A Deep Dive Into Component Lifecycle Management 🔄


📈 30.25 Punkte
🔧 Programmierung

🔧 Svelte + Manifest = Giving Svelte a proper backend with 7 lines of code 🧡🦚


📈 29.31 Punkte
🔧 Programmierung

🔧 Svelte Series-2: How to install Svelte


📈 29.31 Punkte
🔧 Programmierung

🔧 kbar-svelte-mini - ctrl+k menu for your Svelte website


📈 29.31 Punkte
🔧 Programmierung

🔧 Spice Up Your Svelte App with Sound Interactions using svelte-sound 😎


📈 29.31 Punkte
🔧 Programmierung

🕵️ Medium CVE-2021-29261: Svelte Svelte


📈 29.31 Punkte
🕵️ Sicherheitslücken

🔧 Understanding React, Component Lifecycle, and UseEffect Hook


📈 26.6 Punkte
🔧 Programmierung

🔧 Understanding Vue Reactivity with Pinia Stores


📈 26.06 Punkte
🔧 Programmierung

🔧 Understanding useEffect vs. Class Component Lifecycle Methods in React Native


📈 25.46 Punkte
🔧 Programmierung

🔧 Exploring the React component lifecycle: A guide to understanding the different phases.


📈 25.46 Punkte
🔧 Programmierung

🔧 Angular Fundamentals: Understanding Angular Component Lifecycle


📈 25.46 Punkte
🔧 Programmierung

🔧 Svelte Series-6: Lifecycle


📈 25.46 Punkte
🔧 Programmierung

🔧 Show dev: Flowbite Svelte - Open-source UI component library


📈 23.31 Punkte
🔧 Programmierung

🔧 Java, Jiu-Jitsu, and Reactivity: Mastering the Backend Without Blocking!


📈 21.19 Punkte
🔧 Programmierung

🔧 Build a Web App with Oats~i – Lesson 2: Reactivity and Data Manager


📈 21.19 Punkte
🔧 Programmierung

🔧 An Animated Guide to Vue 3 Reactivity and Internals


📈 21.19 Punkte
🔧 Programmierung

🔧 Understanding Svelte 5 Runes: $derived vs $effect


📈 20.66 Punkte
🔧 Programmierung

🔧 Getting Started with React and the Component Lifecycle


📈 20.59 Punkte
🔧 Programmierung

🔧 How to Build Your Own Vue-like Reactivity System from Scratch


📈 20.05 Punkte
🔧 Programmierung

🔧 Fun-grained reactivity in Angular: Part 1 – Primitives


📈 20.05 Punkte
🔧 Programmierung

🔧 Angular Internals: How Reactivity Works with Zone.js


📈 20.05 Punkte
🔧 Programmierung

🔧 Scheduling Derivations in Reactivity


📈 20.05 Punkte
🔧 Programmierung

🔧 A Fresh Take On Reactivity


📈 20.05 Punkte
🔧 Programmierung

🔧 Reactivity in Javascript


📈 20.05 Punkte
🔧 Programmierung

🔧 Learn JavaScript Reactivity: How to Build Signals from Scratch


📈 20.05 Punkte
🔧 Programmierung

matomo