Performance: Context API vs stores
This affects how state updates propagate and how many components re-render, impacting interaction responsiveness and rendering speed.
import { writable } from 'svelte/store'; // store.js export const userStore = writable(null); // Any component import { userStore } from './store.js'; // Use $userStore in markup
import { setContext, getContext } from 'svelte'; // Parent.svelte setContext('user', userStore); // Child.svelte const user = getContext('user'); // Child uses $user directly in markup
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Context API with reactive stores | High - many components subscribe | Multiple reflows per update | High paint cost due to frequent updates | [X] Bad |
| Svelte stores with selective subscriptions | Low - only subscribed components update | Single or minimal reflows | Lower paint cost | [OK] Good |
| Context API for static data | Minimal DOM operations | No reflows triggered by context | Minimal paint cost | [OK] Good |
import { setContext, getContext } from 'svelte';
// Parent.svelte
setContext('color', 'blue');
// Child.svelte
const color = getContext('color');
color be inside Child.svelte?import { writable } from 'svelte/store';
const count = writable(0);
function increment() {
count = count + 1;
}Pass the test and this pattern moves unknown