Performance: Custom store logic
Custom store logic affects how reactive data updates propagate and how many DOM updates happen, impacting interaction responsiveness and rendering speed.
import { writable } from 'svelte/store'; function createGoodStore() { const { subscribe, set, update } = writable(0); return { subscribe, increment: () => { // defer heavy computation outside update setTimeout(() => { update(n => n + 1); }, 0); } }; } export const goodStore = createGoodStore();
import { writable } from 'svelte/store'; function createBadStore() { const { subscribe, set, update } = writable(0); return { subscribe, increment: () => { update(n => { // heavy computation inside update for (let i = 0; i < 1000000; i++) {} return n + 1; }); } }; } export const badStore = createBadStore();
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous logic in store update | Multiple reactive DOM updates | Triggers multiple reflows | High paint cost due to blocking | [X] Bad |
| Lightweight async store update | Minimal reactive DOM updates | Single reflow per update | Low paint cost, smooth rendering | [OK] Good |
writable and uses update to change the value.set with a function argument, which is invalid. import { readable } from 'svelte/store'; function createStore() { const { subscribe } = readable(0); return { subscribe, increment: () => {} }; } uses readable which is read-only. import { store } from 'svelte/store'; function createStore() { return { subscribe: () => {}, increment: () => {} }; } imports a non-existent store.counter.increment() twice?import { writable } from 'svelte/store';
function createCounter() {
const { subscribe, update } = writable(0);
return {
subscribe,
increment: () => update(n => n + 1)
};
}
const counter = createCounter();
counter.subscribe(value => console.log(value));
counter.increment();
counter.increment();import { writable } from 'svelte/store';
function createTimer() {
const { subscribe, set } = writable(0);
let interval = null;
return {
subscribe,
start: () => {
interval = setInterval(() => set(n + 1), 1000);
},
stop: () => clearInterval(interval)
};
}set(n + 1) but n is not defined anywhere in scope.update should be used or the current value tracked. Using set with undefined n causes an error.set(n + 1) without defining n -> Option Cupdate and checks if the item exists before adding, preventing duplicates.set with a function argument, which is invalid. import { readable } from 'svelte/store'; function createList() { const { subscribe } = readable([]); return { subscribe, add: (item) => {} }; } uses readable which is read-only. import { writable } from 'svelte/store'; function createList() { const { subscribe, update } = writable([]); return { subscribe, add: (item) => update(list => [...list, item]) }; } adds items without checking duplicates.Pass the test and this pattern moves unknown