0
0
Svelteframework~15 mins

Writable stores in Svelte - Deep Dive

Choose your learning style9 modes available
Overview - Writable stores
What is it?
Writable stores in Svelte are special objects that hold data you can read and change. They let different parts of your app share and update information easily. When the data changes, all parts using it automatically update on the screen. This helps keep your app in sync without extra work.
Why it matters
Without writable stores, sharing and updating data between components would be messy and repetitive. You would have to pass data through many layers or write extra code to keep everything updated. Writable stores solve this by providing a simple, central place to hold and change data, making apps smoother and easier to build.
Where it fits
Before learning writable stores, you should understand basic Svelte components and how to use reactive variables. After mastering writable stores, you can learn about derived stores and custom stores to handle more complex data flows.
Mental Model
Core Idea
Writable stores are like shared notebooks where components write and read data, and everyone sees updates instantly.
Think of it like...
Imagine a whiteboard in a room where everyone can write notes and erase them. When one person changes something, everyone else sees the change right away without asking.
┌───────────────┐
│ Writable Store│
│  (data box)   │
└──────┬────────┘
       │
       ▼
┌───────────────┐   ┌───────────────┐
│ Component A   │   │ Component B   │
│ reads & writes│   │ reads & writes│
└───────────────┘   └───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is a writable store
🤔
Concept: Writable stores hold data that can be read and changed by components.
In Svelte, writable stores are created using the writable() function from 'svelte/store'. You start with a value, and the store lets you get or set that value. For example: import { writable } from 'svelte/store'; const count = writable(0); This creates a store holding the number 0.
Result
You have a store named count that holds 0 and can be changed later.
Understanding that writable stores hold data that can change is the base for reactive shared state in Svelte.
2
FoundationSubscribing to store changes
🤔
Concept: Components can listen to store updates to react when data changes.
You can subscribe to a writable store to get its current value and be notified when it changes. In Svelte components, you use the $ prefix to auto-subscribe:

Count is {$count}

This means the component shows the current count and updates automatically when count changes.
Result
The component displays the current count and updates the display when count changes.
Knowing that $store syntax auto-subscribes makes it easy to keep UI in sync with data.
3
IntermediateUpdating writable store values
🤔Before reading on: do you think you can change a writable store's value directly or only through special methods? Commit to your answer.
Concept: Writable stores provide methods to update their value safely and notify subscribers.
Writable stores have set() and update() methods: - set(newValue) replaces the value. - update(fn) changes the value based on the current one. Example: count.set(5); // sets count to 5 count.update(n => n + 1); // increases count by 1
Result
The store's value changes and all subscribers update accordingly.
Understanding set and update methods helps you change data predictably and trigger UI updates.
4
IntermediateUsing writable stores across components
🤔Before reading on: do you think writable stores must be created inside each component or can be shared globally? Commit to your answer.
Concept: Writable stores can be shared between components by exporting them from a module.
Create a store in a separate file, for example store.js: import { writable } from 'svelte/store'; export const count = writable(0); Then import and use count in any component:

Count is {$count}

Result
Multiple components share and update the same count value, staying in sync.
Knowing stores can be shared globally enables building coordinated, interactive apps.
5
IntermediateUnsubscribing from writable stores
🤔
Concept: Subscriptions can be stopped to avoid memory leaks or unnecessary updates.
When you subscribe manually, writable stores return an unsubscribe function: const unsubscribe = count.subscribe(value => { console.log(value); }); // Later, stop listening: unsubscribe(); In Svelte components, the $ prefix handles this automatically.
Result
You control when to stop listening to store changes, saving resources.
Understanding unsubscribe prevents bugs and performance issues in complex apps.
6
AdvancedCustom writable stores with extra logic
🤔Before reading on: do you think writable stores can only hold simple data or can they include custom methods? Commit to your answer.
Concept: You can create writable stores with custom methods to add behavior beyond simple get/set.
A custom store is a function returning an object with subscribe, set, update, and extra methods: import { writable } from 'svelte/store'; function createCounter() { const { subscribe, set, update } = writable(0); return { subscribe, increment: () => update(n => n + 1), decrement: () => update(n => n - 1), reset: () => set(0) }; } export const counter = createCounter();
Result
You get a store with extra methods to control data in a clear way.
Knowing how to build custom stores lets you encapsulate logic and keep components clean.
7
ExpertWritable stores and reactivity internals
🤔Before reading on: do you think writable stores update components immediately or batch updates? Commit to your answer.
Concept: Writable stores notify subscribers synchronously but Svelte batches DOM updates for efficiency.
When you call set or update, the store calls all subscriber functions immediately with the new value. However, Svelte batches changes to the DOM so multiple updates in one tick only cause one re-render. This keeps UI fast and consistent. Also, stores use a subscription system that tracks active listeners to avoid unnecessary work.
Result
Components update smoothly without flicker or wasted work, even with many store changes.
Understanding this helps debug subtle timing bugs and optimize performance in large apps.
Under the Hood
Writable stores keep an internal value and a list of subscriber functions. When the value changes via set or update, the store calls each subscriber with the new value. In Svelte components, the $ prefix auto-subscribes and triggers reactive updates. Svelte batches DOM changes after all store notifications to avoid repeated rendering.
Why designed this way?
This design balances simplicity and performance. Immediate subscriber calls keep data consistent, while batching DOM updates prevents slow UI. The subscription model allows multiple components to share data without tight coupling. Alternatives like global event buses were more complex and error-prone.
┌───────────────┐
│ Writable Store│
│  (value +    │
│ subscribers) │
└──────┬────────┘
       │ set/update
       ▼
┌───────────────┐
│ Notify Subs   │
│ (call funcs)  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Svelte Reactivity │
│ (batch DOM updates)│
└─────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: do you think writable stores automatically save data to local storage? Commit yes or no.
Common Belief:Writable stores automatically keep data saved in the browser so it persists after refresh.
Tap to reveal reality
Reality:Writable stores only hold data in memory. To save data persistently, you must add code to sync with local storage or other storage.
Why it matters:Assuming stores save data leads to lost user data after refresh, causing bugs and bad user experience.
Quick: do you think you can mutate the store's value directly without set or update? Commit yes or no.
Common Belief:You can change the value inside a writable store by modifying it directly, like changing an object property.
Tap to reveal reality
Reality:You must use set or update to change the store's value. Direct mutation won't notify subscribers, so UI won't update.
Why it matters:Direct mutation causes UI to stay out of sync, leading to confusing bugs.
Quick: do you think writable stores are only for simple data types? Commit yes or no.
Common Belief:Writable stores are only useful for simple values like numbers or strings, not complex objects or arrays.
Tap to reveal reality
Reality:Writable stores can hold any JavaScript value, including objects and arrays, but you must update them immutably to trigger updates.
Why it matters:Misunderstanding this limits store use and causes bugs when mutating complex data without proper updates.
Quick: do you think multiple components using the same writable store get independent copies? Commit yes or no.
Common Belief:Each component gets its own copy of the writable store's data, so changes in one don't affect others.
Tap to reveal reality
Reality:All components share the same store instance and data. Changes in one component update all others.
Why it matters:Thinking stores are independent causes confusion when data changes unexpectedly across components.
Expert Zone
1
Writable stores notify subscribers synchronously, but Svelte batches DOM updates asynchronously for performance.
2
Custom writable stores can include derived values or side effects, but must carefully manage subscriptions to avoid leaks.
3
Using update() with immutable patterns prevents subtle bugs caused by direct mutation of complex data inside stores.
When NOT to use
Writable stores are not ideal for very large or deeply nested state where specialized state management libraries like Redux or Zustand may be better. Also, for purely read-only data, derived or readable stores are more appropriate.
Production Patterns
In real apps, writable stores often hold user input, UI state, or shared data like authentication status. Custom stores encapsulate logic like counters or form validation. Stores are combined with derived stores and context API for scalable state management.
Connections
Observer pattern
Writable stores implement the observer pattern by letting subscribers watch for changes.
Understanding writable stores as observers clarifies how components react to data changes automatically.
Reactive programming
Writable stores are a reactive programming tool that updates dependents when data changes.
Knowing reactive programming principles helps grasp why stores trigger UI updates without manual DOM manipulation.
Shared memory in operating systems
Writable stores act like shared memory where multiple processes (components) read and write data.
Seeing writable stores as shared memory helps understand synchronization and update propagation challenges.
Common Pitfalls
#1Mutating store value directly without set or update.
Wrong approach:count.subscribe(value => { value.count = value.count + 1; });
Correct approach:count.update(n => n + 1);
Root cause:Misunderstanding that direct mutation does not notify subscribers, so UI does not update.
#2Creating writable stores inside components causing isolated state.
Wrong approach:In ComponentA.svelte: import { writable } from 'svelte/store'; const count = writable(0);
Correct approach:Create store in separate module: // store.js import { writable } from 'svelte/store'; export const count = writable(0); // ComponentA.svelte import { count } from './store.js';
Root cause:Not sharing store instance leads to each component having independent state, breaking synchronization.
#3Not unsubscribing from manual subscriptions causing memory leaks.
Wrong approach:const unsubscribe = count.subscribe(value => console.log(value)); // never calling unsubscribe()
Correct approach:const unsubscribe = count.subscribe(value => console.log(value)); unsubscribe(); // when no longer needed
Root cause:Forgetting to unsubscribe keeps listeners alive, wasting memory and CPU.
Key Takeaways
Writable stores hold data that components can read and change, enabling shared reactive state.
Using set() and update() methods ensures changes notify all subscribers and update the UI.
The $ prefix in Svelte components auto-subscribes to stores, keeping the UI in sync effortlessly.
Writable stores can be shared globally by exporting them from modules, allowing multiple components to coordinate.
Custom writable stores let you add methods and logic, making state management cleaner and more powerful.