0
0
SvelteConceptBeginner · 4 min read

$effect in Svelte 5: How It Works and When to Use

$effect in Svelte 5 is a special reactive function that runs side effects whenever its dependencies change. It helps you perform tasks like fetching data or updating the DOM in response to reactive state changes, similar to React's useEffect but simpler and built into Svelte's reactivity.
⚙️

How It Works

Imagine you have a plant that needs watering whenever the sunlight changes. In Svelte 5, $effect acts like a smart gardener who watches the sunlight (your reactive variables) and waters the plant (runs your side effect) only when needed.

Technically, $effect is a reactive function that automatically tracks the variables you use inside it. When any of those variables change, Svelte runs the $effect callback again. This makes it easy to keep your side effects in sync with your component's state without manually managing subscriptions or cleanup.

It also supports cleanup by returning a function inside the $effect callback, which runs before the effect re-runs or when the component is destroyed. This helps avoid memory leaks or stale data.

💻

Example

This example shows how $effect updates the document title whenever the count variable changes.

svelte
let count = 0;

$effect(() => {
  document.title = `Count is ${count}`;
  return () => {
    // Cleanup if needed (not required here)
  };
});

function increment() {
  count += 1;
}
Output
A button labeled 'Increment' that when clicked increases count and updates the browser tab title to 'Count is X'.
🎯

When to Use

Use $effect when you need to run code that reacts to changes in your component's state but is not directly part of the UI rendering. Examples include:

  • Updating the document title or meta tags
  • Fetching data when a parameter changes
  • Setting up or cleaning event listeners
  • Interacting with browser APIs like localStorage or timers

It is perfect for keeping side effects clean and tied to reactive data without extra boilerplate.

Key Points

  • $effect runs automatically when its reactive dependencies change.
  • It tracks variables used inside its callback without manual dependency lists.
  • Supports cleanup by returning a function inside the callback.
  • Helps keep side effects in sync with component state simply.
  • Built-in Svelte 5 feature replacing older reactive statement patterns for side effects.

Key Takeaways

$effect runs side effects automatically when reactive variables change.
It simplifies managing effects and cleanup tied to component state.
Use it for tasks like data fetching, DOM updates, or event listeners.
It tracks dependencies without manual lists, reducing bugs.
Cleanup functions prevent memory leaks by running before re-execution or destruction.