Performance: Context vs stores decision
MEDIUM IMPACT
This affects how state sharing impacts page load speed and interaction responsiveness in Svelte apps.
Using a Svelte store for global reactive state: // userStore.js import { writable } from 'svelte/store'; export const user = writable(null); // AnyComponent.svelte <script> import { user } from './userStore.js'; user.subscribe(value => { /* react to changes */ }); </script>
Using context to pass state deeply and across many components manually: // Parent.svelte <script> import { setContext } from 'svelte'; import { user } from './userStore.js'; setContext('user', user); </script> // DeepChild.svelte <script> import { getContext } from 'svelte'; const user = getContext('user'); user.subscribe(value => { /* react to changes */ }); </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using context for global reactive state | High due to many subscriptions | Multiple reflows from unnecessary updates | High paint cost from frequent re-renders | [X] Bad |
| Using stores for global reactive state | Optimized subscriptions only where needed | Minimal reflows limited to subscribed components | Lower paint cost due to selective updates | [OK] Good |
| Using stores for static data | Unnecessary subscription overhead | Unneeded reflows on rare changes | Moderate paint cost | [!] OK |
| Using context for static data | No subscriptions, minimal DOM ops | No reflows triggered by data changes | Minimal paint cost | [OK] Good |