Svelte State 06 🧡 Avoiding $effect() Anti-Patterns — Replacing unnecessary $effect chains with $derived(), $derived.by(), and event handlers
In the modern Svelte 5 reactivity model, $effect() is the most powerful tool for synchronization, but it is also the most frequently misused. Developers transitioning from other frameworks often treat effects as the primary mechanism for responding to state changes, creating chains where one effect updates a piece of state, which triggers a second effect, which updates another. This “reactive waterfall” makes the application flow difficult to reason about and can introduce subtle bugs or performance overhead.
This chapter explores how to identify when you are misusing $effect() and how to replace those patterns with the more appropriate primitives. We will cover the mechanics of reactive derivation, the use of event handlers for user-driven logic, and the specific cases where synchronization via $effect() is actually required.
Key point: $effect() is designed exclusively for side effects that synchronize the external world (like DOM nodes or logs) with your state; if your goal is to calculate a value based on other state, you should always use $derived() or $derived.by() instead.
Why $effect() anti-patterns exist
The imperative mindset problem. Many developers are accustomed to imperative state management, where an action triggers a chain of “re-calculations” via lifecycle hooks. When forced into a reactive environment, the instinct is to continue this procedural chain rather than relying on the declarative nature of Svelte’s signals.
The missing reactivity primitives problem. Before the introduction of $derived and $derived.by as first-class citizens, developers had fewer options for computing values. This led to a legacy of using side effects to store calculated state, a pattern that persists even though it is no longer the recommended approach.
The synchronization vs. derivation confusion. Developers often struggle to distinguish between “derivation” (calculating a new value from existing data) and “synchronization” (applying a change to an external system). $effect() is for the latter, but because it feels like a “listener,” it is often drafted for the former.
The infinite loop trap. When an effect updates the very state it depends on, it can trigger itself. While Svelte 5 is resilient, these cycles create unpredictable rendering paths and performance degradation as the framework constantly reconciles state changes.
The lifecycle complexity issue. Effects have complex lifecycles involving setup and teardown. Using them to derive state means creating and destroying these complex reactive observers when simple arithmetic or boolean operations would suffice.
a. Replacing chains with $derived()
The most common anti-pattern is using an $effect() to set a state variable based on other state. This is inefficient because it creates a delay between the state update and the derivative calculation. $derived() is synchronous and computes its value the moment the dependencies change, ensuring the UI remains perfectly in sync with the source of truth.
let count = $state(0);
let doubled = $state(0);
// ❌ Anti-pattern: Syncing state manually via effect
$effect(() => {
doubled = count * 2;
});
The issue here is that doubled effectively becomes an “event” that fires after the render cycle. If a component reads doubled while the effect is still pending, it might get the stale value. Using $derived() moves this logic into the reactive graph itself.
// ✅ Better: Declarative derivation
let count = $state(0);
let doubled = $derived(count * 2);
When count updates, doubled is updated immediately as part of the same transaction. There is no manual syncing, no extra effect cycle, and no risk of stale data.
b. Complex logic with $derived.by()
Sometimes derivation requires more than a simple expression. When you need multiple lines of code, local variables, or conditionals to calculate a derived state, the $derived() expression becomes unreadable. Previously, developers would jump to an $effect() to solve this, but $derived.by() allows you to run a block of code to compute a value while maintaining the same performance and synchronicity.
// ❌ Anti-pattern: Using effect for logic
let items = $state([1, 2, 3]);
let total = $state(0);
$effect(() => {
total = items.reduce((a, b) => a + b, 0);
});
Using $derived.by() encapsulates this computation into a pure function that is part of the reactivity graph. It returns the result of the function, ensuring that the dependency tracking is just as precise as a simple expression.
// ✅ Better: Using derived.by for complex logic
let items = $state([1, 2, 3]);
let total = $derived.by(() => {
let sum = 0;
for (const item of items) {
sum += item;
}
return sum;
});
This ensures that total is only recomputed when items changes, and importantly, it remains read-only to the rest of the component, enforcing a clear unidirectional data flow.
c. Using event handlers for discrete state updates
Another frequent anti-pattern is using an $effect() to respond to user actions. If you have a button that modifies state, and you want that modification to cause a secondary change, you should perform both updates in the event handler rather than using an effect to “react” to the first update.
// ❌ Anti-pattern: Chained effect for user action
function increment() {
count++;
}
$effect(() => {
if (count > 10) log("Limit reached");
});
If the business logic dictates that exceeding 10 requires logging, that is part of the “incrementing” event. Moving this to an effect adds a layer of indirection that obscures the intent.
// ✅ Better: Direct handling in the event
function increment() {
count++;
if (count > 10) log("Limit reached");
}
By keeping the secondary state change or action within the same event handler, you preserve the call stack and make the behavior predictable. You are not “reacting” to state; you are executing a command that results in state changes.
Complete Example Session
// ============================================
// PART 1: THE BAD EFFECT CHAIN
// ============================================
let firstName = $state("John");
let lastName = $state("Doe");
let fullName = $state("");
$effect(() => {
fullName = `${firstName} ${lastName}`; // ❌ Syncing manually
});
// ============================================
// PART 2: THE DERIVED REPLACEMENT
// ============================================
let firstName = $state("John");
let lastName = $state("Doe");
let fullName = $derived(`${firstName} ${lastName}`); // ✅ Proper derivation
// ============================================
// PART 3: COMPLEX DERIVATION VIA DERIVED.BY
// ============================================
let inventory = $state([{ price: 10 }, { price: 20 }]);
let tax = $derived.by(() => {
const subtotal = inventory.reduce((a, b) => a + b.price, 0);
return subtotal * 0.15; // Complex calculation
});
// ============================================
// PART 4: EVENT HANDLER LOGIC
// ============================================
function updateScore(points: number) {
score += points;
if (score > 100) notifyWinner(); // Logic happens here, not in an effect
}
// ============================================
// PART 5: CLEANUP SYNCHRONIZATION
// ============================================
$effect(() => {
const interval = setInterval(tick, 1000);
return () => clearInterval(interval); // ✅ Synchronization belongs here
});
This sequence demonstrates the transition from state-syncing effects to declarative derivations and direct event-driven logic.
Quick Reference
Reactive Primitives
| Primitive | Usage | Best For |
|---|---|---|
$state | Data | Storing the source of truth |
$derived | Computation | Simple calculations |
$derived.by | Logic | Complex calculations |
$effect | Sync | DOM, logs, API, timers |
Logic Flow
| Goal | Mechanism |
|---|---|
| Read-only computed value | $derived |
| Multi-step calculation | $derived.by |
| Updating multiple states at once | Event Handler |
| Interacting with browser APIs | $effect |
Best Practices
✅ Do This:
let price = $state(100);
let tax = $derived(price * 0.2); // ✅
let total = $derived.by(() => price + tax); // ✅
function handleClick() { count++; log("click"); } // ✅
$effect(() => { element.focus(); }); // ✅
let isReady = $derived(user.name !== ""); // ✅
❌ Don’t Do This:
let doubled = $state(0);
$effect(() => { doubled = count * 2; }); // ❌
$effect(() => { total = count + tax; }); // ❌
function inc() { count++; } $effect(() => { log(count); }); // ❌
$effect(() => { if (count > 0) isActive = true; }); // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Stale values | Effect runs after render | Use $derived |
| Infinite loops | Effect updates its own dependency | Use Event Handlers |
| Performance hit | Too many effects firing | Batch in handler |
| Readability | Effect contains business logic | Move to helper function |
| Memory leaks | Missing cleanup in effect | Add return function |
Real-World Examples
1. Simple Derivation
let price = $state(10);
let total = $derived(price * 1.1);
2. Complex Calculation
let cart = $state([]);
let total = $derived.by(() => cart.reduce((a, b) => a + b.price, 0));
3. Handling User Input
function onInput(e) {
value = e.target.value;
validate(value); // No effect needed
}
4. Browser API Sync
$effect(() => {
document.title = `Score: ${score}`;
});
5. Timer Cleanup
$effect(() => {
const t = setTimeout(trigger, 1000);
return () => clearTimeout(t);
});
6. Form Validation
let isValid = $derived(email.includes("@"));
7. Filtered Lists
let filtered = $derived(list.filter(i => i.active));
8. Conditional Formatting
let color = $derived(score > 10 ? 'red' : 'green');
9. Chained Calculations
let sub = $derived(a + b);
let tax = $derived(sub * 0.1);
10. Initializing State
// Do this in the variable declaration
let val = $state(localStorage.getItem('key') || 'default');
Visual
The Reactive Graph
┌──────────────────────────────────────────────┐
│ $state ──► $derived ──► Component UI │
│ │
│ The flow is unidirectional and predictable │
│ without extra effect layers. │
└──────────────────────────────────────────────┘
The Effect Anti-Pattern
┌──────────────────────────────────────────────┐
│ $state ──► $effect ──► $state (Chain) │
│ │
│ This creates unnecessary reconciliation │
│ cycles and delays UI updates. │
└──────────────────────────────────────────────┘
Event-Driven Logic
┌──────────────────────────────────────────────┐
│ User Action ──► Event Handler │
│ │ │
│ ├──► Update State A │
│ └──► Update State B │
│ │
│ All updates happen in one block. │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
$state | Primary data container |
$derived | One-line computation |
$derived.by | Multi-line computation |
$effect | Browser/External sync |
| Cleanup | Required for $effect |
| Anti-pattern | Chaining state in $effect |
Key takeaways:
- Use
$derivedfor computed data. It is the direct replacement for manual synchronization and ensures data is always current. $derived.bymanages complex logic. Use it for blocks of code that require local variables or loops to calculate a single reactive value.- Keep event logic in event handlers. Never use an effect to trigger secondary state changes resulting from a specific user interaction.
- Only use
$effectfor external synchronization. If you are touching the DOM, logs, or third-party libraries, the effect is the correct place. - Effects require cleanup. Always return a teardown function to prevent memory leaks and ghost subscriptions.
Remember: Svelte’s reactivity is a directed graph. By minimizing the number of nodes in that graph—specifically by avoiding unnecessary $effect observers—you ensure that your application state flows predictably from source to derived result without unnecessary overhead. When in doubt, prefer a simple expression or an event handler over an effect.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!