0
0
SvelteHow-ToBeginner · 3 min read

How to Create Derived Store in Svelte: Syntax and Example

In Svelte, create a derived store using the derived function from svelte/store. It takes one or more input stores and a callback to compute the derived value, updating automatically when inputs change.
📐

Syntax

The derived function creates a new store based on one or more existing stores. It takes these arguments:

  • stores: a single store or an array of stores to derive from.
  • callback: a function that receives the current values of the input stores and returns the derived value.
  • initial_value (optional): a starting value for the derived store.

The derived store updates automatically when any input store changes.

javascript
import { derived } from 'svelte/store';

const derivedStore = derived(
  inputStoreOrStores,
  ($inputStores, set) => {
    // compute derived value
    const result = /* some calculation with $inputStores */;
    set(result);
  },
  initialValue // optional
);
💻

Example

This example shows how to create a derived store that calculates the double of a number stored in a writable store.

javascript
import { writable, derived } from 'svelte/store';

const count = writable(5);

const double = derived(count, $count => $count * 2);

// Usage example (in a Svelte component):
// <script>
//   import { count, double } from './stores.js';
// </script>
// <p>Count: {$count}</p>
// <p>Double: {$double}</p>
Output
Count: 5 Double: 10
⚠️

Common Pitfalls

Common mistakes when creating derived stores include:

  • Not subscribing to the derived store in the component, so it never updates.
  • Passing a non-store value instead of a store to derived.
  • Forgetting to return or call set inside the callback when using the second argument form.
  • Using the wrong number of arguments or mixing single and multiple stores incorrectly.

Always ensure input stores are valid Svelte stores and that the derived callback returns the computed value or calls set.

javascript
import { writable, derived } from 'svelte/store';

const count = writable(3);

// Wrong: passing a number instead of a store
// const wrongDerived = derived(3, $val => $val * 2); // ❌

// Correct:
const correctDerived = derived(count, $count => $count * 2); // ✅
📊

Quick Reference

Key points to remember when using derived stores in Svelte:

  • Use derived to create a store based on other stores.
  • The callback receives current values of input stores as arguments.
  • Return the derived value directly or use the set function for async updates.
  • Derived stores update automatically when inputs change.

Key Takeaways

Use Svelte's built-in derived function to create stores based on other stores.
The derived callback receives current input store values and returns the computed result.
Always pass valid stores as inputs to derived, not raw values.
Subscribe to derived stores in components to see updates.
You can provide an initial value for the derived store if needed.