Performance: Store contract (subscribe method)
This affects how efficiently components update when store data changes, impacting interaction responsiveness and rendering speed.
let previous; const unsubscribe = store.subscribe(value => { if (value !== previous) { previous = value; efficientUpdate(value); } });
const unsubscribe = store.subscribe(value => { // heavy computation or DOM updates here expensiveUpdate(value); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Subscribe triggers update on every change | Many DOM updates | Multiple reflows per update | High paint cost | [X] Bad |
| Subscribe updates only on real data change | Minimal DOM updates | Single reflow per real change | Low paint cost | [OK] Good |
subscribe method of a Svelte store do?subscribesubscribe method allows you to listen to changes in the store's value.subscribe enablescount?subscribe as a method on the store with a callback.count.subscribe with a function to receive updates.import { writable } from 'svelte/store';
const count = writable(0);
const unsubscribe = count.subscribe(value => console.log(value));
count.set(5);
unsubscribe();
count.set(10);unsubscribe() stops listening, so setting to 10 logs nothing.import { writable } from 'svelte/store';
const count = writable(0);
count.subscribe(value => console.log(value));
count.unsubscribe();subscribe method returns an unsubscribe function to stop listening.unsubscribe directly on the store is invalid; you must call the function returned by subscribe.subscribe method to follow the store contract?run and call it immediately with the current value.run(value) and returns a function that logs 'unsubscribed'.run(value), C lacks run parameter, D misses returning the unsubscribe function.Pass the test and this pattern moves unknown