Performance: Context with stores
This affects how efficiently state is shared and updated across components without unnecessary DOM updates or re-renders.
import { writable } from 'svelte/store'; import { setContext, getContext } from 'svelte'; const count = writable(0); setContext('countStore', count); // In nested components const count = getContext('countStore');
import { writable } from 'svelte/store'; const count = writable(0); // Passing store as a prop through many components <ComponentA count={count} /> // Each intermediate component passes count down as prop
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Passing stores via props through many components | Many prop updates and component re-renders | Multiple reflows triggered by each update | Higher paint cost due to repeated updates | [X] Bad |
| Providing stores via Svelte context | Only subscribed components update | Single reflow per store update | Lower paint cost due to targeted updates | [OK] Good |
setContext and getContext with stores?setContext and getContextsetContext from 'svelte' with a key and a value (store).setContext('key', store); to provide the store under a key./* Parent.svelte */
setContext('count', writable(0)); to share a reactive store.getContext('count'); and can call update() or set() to change the value, reflecting everywhere.Pass the test and this pattern moves unknown