Svelte State 01 🧡 Local vs. Shared State — Understanding $state() and $derived()
Modern Svelte state management revolves around the concept of “Runes,” which provide a standardized, fine-grained reactive model that works consistently both inside and outside of components. In Svelte 5, state is no longer tethered to the component lifecycle in the way it was with old-fashioned variables; instead, $state() and $derived() are reactive primitives that enable seamless tracking of dependencies.
This chapter explores how to define local state using $state() and computed values using $derived(). We will also address the architecture of application data: when to keep state local to a single component, when to “lift” it to a parent, and when to move it into shared modules or context for global accessibility. By understanding the boundaries of state ownership, you can prevent unnecessary prop-drilling and create a more predictable data flow.
Key point: $state() is for mutable values that trigger UI updates, $derived() is for read-only values computed from other state, and state should be shared by elevating it into external JavaScript/TypeScript modules or Svelte Context rather than relying solely on component props.
Why exists
- The Prop Drilling problem. Passing data through five layers of components just to reach a deep child is inefficient and makes refactoring difficult.
- The Reactivity Coupling problem. Old Svelte state was bound to the component instance; runes allow you to define reactive logic in standalone files, separate from UI definitions.
- The Derived Value problem. Manually managing complex updates for calculated fields (like a filtered list based on a search string) was error-prone;
$derived()automates this calculation. - The Memory Leak problem. Improperly scoped state can persist after a component is destroyed; clear ownership patterns help avoid these leaks.
- The Fine-grained reactivity requirement. Svelte’s signals allow the framework to update only the specific DOM nodes that depend on a piece of state, rather than re-evaluating the entire component tree.
a. Local state with $state()
The $state() rune is the fundamental building block of reactive data. When you declare a variable with $state(), Svelte makes it observable. Any component or function that reads this value will automatically re-run its reactive code whenever the value is reassigned.
let count = $state(0);
function increment() {
count += 1;
}
Local state is preferred whenever the data is only relevant to a single component (like a toggle state for a specific dropdown). Because Svelte 5 runes can be exported from files, the line between “local” and “shared” is now a matter of where you declare the variable, rather than whether it is inside a script tag.
b. Computed state with $derived()
$derived() creates a read-only signal that automatically recomputes its value when its dependencies change. This is the idiomatic way to handle calculated values, such as sorting a list, summing prices in a cart, or formatting strings.
let price = $state(100);
let quantity = $state(2);
// Derived state automatically tracks 'price' and 'quantity'
let total = $derived(price * quantity);
Using $derived() prevents bugs where the UI would otherwise go out of sync because you forgot to manually update a calculated variable. It is computationally efficient because it only recomputes when the underlying dependencies change, not on every component render.
c. Lifting and Sharing State
When two components need access to the same data, you have two primary options: lifting the state or using a shared module. Lifting state involves moving the $state() declaration to the nearest common ancestor and passing it down via props.
// Shared module (state.ts)
export let user = $state({ name: 'Guest' });
// Component A and B can both import the same 'user' object
For true global state (like a user authentication object), moving the declaration into an external .ts or .js file is the superior approach. This removes the state from the component lifecycle entirely, making it accessible from anywhere in your app and easier to test in isolation.
Complete Example Session
// ============================================
// PART 1: LOCAL STATE
// ============================================
let isOpen = $state(false);
// ============================================
// PART 2: DERIVED COMPUTATION
// ============================================
let items = $state([1, 2, 3]);
let count = $derived(items.length);
// ============================================
// PART 3: EXTERNAL MODULE (SHARED STATE)
// ============================================
// store.ts
export let globalTheme = $state('dark');
// ============================================
// PART 4: COMPONENT CONSUMPTION
// ============================================
import { globalTheme } from './store.ts';
function toggle() {
globalTheme = globalTheme === 'dark' ? 'light' : 'dark';
}
These parts show the progression from simple local flags to derived counts and finally to global, module-level state shared across multiple components.
Quick Reference
Rune Comparison
| Rune | Usage | Persistence |
|---|---|---|
$state | Mutable data | Reactive |
$derived | Read-only calculation | Automatically updated |
$effect | Side effects | Runs on state change |
State Ownership Strategy
| Scenario | Strategy |
|---|---|
| UI-only toggle | Local $state |
| Filtered list | $derived from local state |
| User settings | Shared module state |
| Complex form | Lifted to common parent |
Best Practices
✅ Do This:
// Declare state at the top level of the module for sharing
export let sharedCount = $state(0); // ✅
// Use $derived for calculated UI fields
let full = $derived(`${first} ${last}`); // ✅
// Keep state as local as possible
let localToggle = $state(false); // ✅
❌ Don’t Do This:
// Don't over-use global state for UI toggles
// (keep modal state local) // ❌
// Don't re-assign derived state
total = 10; // (Error: derived is read-only) // ❌
// Don't put state inside a function body
// (it will lose reactivity) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Losing reactivity | Destructuring $state object | Don’t destructure, access via key |
| Re-assigning derived | Misunderstanding $derived | Update the source $state |
| Over-sharing | Moving everything to global | Keep local logic in components |
Real-World Examples
1. Counter
let count = $state(0);
2. Full Name
let fullName = $derived(first + ' ' + last);
3. Theme Toggle
export let theme = $state('light');
4. Cart Total
let total = $derived(items.reduce((a, b) => a + b.price, 0));
5. Visibility Toggle
let isVisible = $state(true);
6. Search Filter
let results = $derived(all.filter(i => i.name.includes(query)));
7. Input Binding
<input bind:value={name} />
8. URL Sync
let url = $derived('/path/' + id);
9. State Object
let user = $state({ id: 1, name: 'Dev' });
10. External counter
export let clicks = $state(0);
Visual
Local State Scope
┌──────────────────────────────────────────────┐
│ COMPONENT A │
│ ┌────────────────────────┐ │
│ │ Local State ($state) │ │
│ └────────────────────────┘ │
│ (State dies when component unmounts) │
└──────────────────────────────────────────────┘
Shared State Ownership
┌──────────────────────────────────────────────┐
│ SHARED MODULE (store.ts) │
│ ┌────────────────────────┐ │
│ │ Shared State ($state) │ │
│ └────────────────────────┘ │
│ (State persists across app navigation) │
└──────────────────────────────────────────────┘
Derived Dependency Graph
┌──────────────────────────────────────────────┐
│ $state(A) ──► $derived(C) │
│ $state(B) ──► $derived(C) │
│ │
│ Any change to A or B triggers C update. │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Mutable | $state |
| Calculated | $derived |
| Global | Module-level export |
| Best Practice | Keep it local until shared |
Key takeaways:
- Use
$state()for raw data. It should be your default for any value that changes over time. - Use
$derived()for calculations. It is safer and more performant than manually updating variables in response to changes. - Think about scope. Before making state global, ask if the component can manage it alone.
- Use modules for sharing. Externalizing state into standard JavaScript files is the most robust way to share data across the component tree.
- Respect read-only. Remember that
$derivedis essentially a computed view; you cannot change it directly, only change its sources.
Remember: Svelte’s reactivity model is powerful because it treats state as a first-class citizen regardless of where it lives. By correctly choosing between local $state() and shared module-level exports, and by relying on $derived() for all your UI calculations, you create code that is both highly readable and inherently optimized for the browser.
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!