Performance: setContext
This affects how data is shared between components without prop drilling, impacting rendering and update efficiency.
<Parent>
{#if true}
<Child />
{/if}
<script>
import { setContext } from 'svelte';
setContext('key', data);
</script>
</Parent>
<Child>
<GrandChild />
<script>
import { getContext } from 'svelte';
const data = getContext('key');
</script>
</Child><Parent>
<Child prop={data} />
</Parent>
<Child>
<GrandChild prop={prop} />
</Child>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Prop drilling through many components | High (many props passed) | Multiple reflows per intermediate update | Higher paint cost due to repeated updates | [X] Bad |
| Using setContext for data sharing | Low (direct context access) | Single reflow on update | Lower paint cost with fewer updates | [OK] Good |
setContext in Svelte?setContextsetContext is used to share data or functions from a parent component to its children without passing props explicitly.setContext.setContext in a Svelte component?setContext function signaturesetContext(key, value); where key is a variable or symbol. setContext('key', value); uses a string literal which is discouraged because keys should be unique and not collide. setContext('key'); misses the value argument. setContext(value, 'key'); reverses the arguments.import { setContext } from 'svelte';
const key = {};
setContext(key, 'hello');import { getContext } from 'svelte';
const value = getContext(key);
console.log(value);key is used in parent and childkey is a local constant object. In the child, key is used but not imported or defined, so it is undefined in that scope.getContext(key)key is not defined in the child, this causes a ReferenceError at runtime.setContext:import { setContext } from 'svelte';
const key = Symbol();
setContext(key);setContext usagesetContext function requires two arguments: a key and a value to share.setContext(key); with only one argument, missing the value argument.setContext. Which approach correctly ensures all children can access the function safely?Pass the test and this pattern moves unknown