Performance: Context key patterns
This affects how efficiently components share data without prop drilling, impacting initial load and interaction responsiveness.
const key = Symbol('myKey'); setContext(key, value); // In child const value = getContext(key);
const key = {}; setContext(key, value); // In child const value = getContext(key);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Object literal as context key | Extra context lookups | Multiple reflows | Higher paint cost due to layout thrashing | [X] Bad |
| Symbol as context key | Minimal context lookups | Single reflow | Lower paint cost with stable layout | [OK] Good |
Symbol as a context key in Svelte?Symbol('description'), not with new.export const key = Symbol('myKey'); is correct and common.Child.svelte component?/* key.js */
export const userKey = Symbol('user');
/* Parent.svelte */
import { setContext } from 'svelte';
import { userKey } from './key.js';
setContext(userKey, { name: 'Alice' });
/* Child.svelte */
import { getContext } from 'svelte';
import { userKey } from './key.js';
const user = getContext(userKey);
console.log(user.name);userKey and value { name: 'Alice' }.userKey and calls getContext(userKey), getting the object./* key.js */
export const themeKey = Symbol('theme');
/* Parent.svelte */
import { setContext } from 'svelte';
import { themeKey } from './key.js';
setContext('themeKey', 'dark');
/* Child.svelte */
import { getContext } from 'svelte';
import { themeKey } from './key.js';
const theme = getContext(themeKey);
console.log(theme);themeKey imported from key.js.Pass the test and this pattern moves unknown