Slots, Context and Web Components in Svelte
Three composition tools in Svelte 3: slots pass content in from the outside, the Context API avoids prop drilling, and custom elements make a component reusable independently of any framework.
A reusable card into which every team can put its own header and its own content: the requirement sounds harmless, and yet you cannot solve it cleanly with props alone. In review, the evasive maneuvers then show up – a store where a slot would have been enough; a prop threaded through seven components even though the Context API would have been the shorter route; a component library that only runs under Svelte even though framework-neutral reuse was the actual goal.
Slots, the Context API and custom elements appear side by side in the same components and are therefore easily confused. What tells them apart is the direction in which something flows: markup from the outside into a component, data from the inside back to that markup, values downward through any number of levels of the component tree. If you briefly clarify which of these directions you need before choosing a tool, you have usually made the decision already.
Editorial note (July 2026): The title explicitly refers to Svelte 3. In Svelte 5, snippets and {@render ...} are the preferred way of composition instead of slots; callback props replace many component events in new code. Context and custom elements remain. The historical syntax stays here; the sources also show today’s counterparts.
Slots: passing content in from the outside#
A slot is a placeholder in a component that the caller fills from the outside. The card component decides on the frame, spacing and layout – the caller determines what goes inside. The simplest case is the default slot:
<!-- Card.svelte -->
<div class="card">
<slot>Nothing here yet</slot>
</div>
<style>
.card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 1rem;
}
</style>
The content between the <slot> tags is the fallback: it only appears when the caller passes nothing. The card is then used like this:
<Card>
<p>This paragraph lands inside the card.</p>
</Card>
It gets interesting with named slots. A card often has more than one zone – a header and a body, for example. In the child component you assign names for them; in the call you assign markup to those names:
<!-- Card.svelte -->
<div class="card">
{#if $$slots.header}
<header class="card-header">
<slot name="header"></slot>
</header>
{/if}
<div class="card-body">
<slot></slot>
</div>
</div>
<Card>
<h2 slot="header">Release notes</h2>
<p>Everything else fills the default slot.</p>
</Card>
The $$slots object deserves a quick look. Its keys are the slot names that were actually passed, and that lets you render the structure conditionally. The <header> frame only appears if the caller really passed a header – otherwise you would have an empty, bordered box. That is the difference between a component you enjoy using and one you find awkward.
What matters here is that $$slots only reports the presence of a slot, not its content at runtime. Whether a named slot is filled is decided at compile time based on the call, not by what the caller renders into it later. For the typical task – leaving out the frame when nobody supplies a header – that is exactly enough, and you should not confuse $$slots with a reactive check for empty content. A second point that comes up regularly in reviews: a named slot can only be output in one place in a component. If you render the same named slot twice, you do not get duplicated content but behavior you should not rely on. If you need the same passed-in content in several places, the way forward is slot props or restructuring the component, not a second <slot name="…">.
Slot props: data from the inside out#
Up to this point, content flows in only one direction: from the outside in. The second part reverses that direction, and this is exactly what gets confused most often. Slot props allow the child component to pass data outward to the inserted markup. The classic case is a list that takes care of iterating but leaves the rendering of each entry to the caller:
<!-- List.svelte -->
<script>
export let items = [];
</script>
<ul>
{#each items as item, index}
<li>
<slot name="item" {item} {index}>
{item}
</slot>
</li>
{/each}
</ul>
The child component passes item and index outward through the slot. The caller receives these values with the let: directive and is free to decide what an entry looks like:
<List items={users}>
<span slot="item" let:item let:index>
{index + 1}. {item.name} – {item.role}
</span>
</List>
The list takes care of the loop, keys and structure; the caller brings the concrete rendering and in return receives exactly the data it needs. Keeping these two directions cleanly apart is the core of understanding slots: markup flows in from the outside, data flows from the inside out via slot props. The following diagram captures both paths side by side.
flowchart LR
Parent["Parent<br/><List let:item>"]
Child["List.svelte<br/><slot name='item' {item}>"]
Render["Rendered <li>"]
Parent -- "markup (outside in)" --> Child
Child -- "slot props: item, index (inside out)" --> Parent
Child --> RenderContext: passing through the tree without prop drilling#
Slots solve the question of how to give content to a direct child component. They do not help when a value is needed several levels deep. Imagine a toolbar whose individual buttons want to register with it. Between the toolbar and the button there may be groups, dividers, wrappers. Passing the registration callback through each of these levels as a prop is tedious and makes intermediate components depend on details that are none of their business. This passing along is called prop drilling, and the Context API is the direct answer to it.
The provider component stores a value under a key, and every descendant component can retrieve it under the same key:
<!-- Toolbar.svelte -->
<script>
import { setContext } from 'svelte';
const buttons = [];
function registerButton(id) {
buttons.push(id);
}
setContext('toolbar', { registerButton });
</script>
<div class="toolbar">
<slot></slot>
</div>
<!-- ToolbarButton.svelte -->
<script>
import { getContext } from 'svelte';
export let id;
const toolbar = getContext('toolbar');
toolbar.registerButton(id);
</script>
<button on:click>
<slot></slot>
</button>
The button finds its toolbar no matter how many levels lie in between. No prop travels through the intermediate components. By the way, the key may be any value – a string as here, a symbol or an object; a symbol reliably protects against name collisions in larger repositories.
The scope of context is strictly limited to the subtree below the provider. A sibling component that does not hang under the same setContext component does not see the value – context flows only downward, never sideways and never upward. If a child component itself calls setContext with the same key, it shadows the value for its own subtree without changing the value further up; resolution therefore follows the instance hierarchy, not the order in the source code. If you are not sure whether a key was set at all, you can check with hasContext instead of relying on an undefined from getContext – that makes the failure case explicit instead of silent.
Two pitfalls come up with remarkable regularity. The first: setContext has to be called synchronously during the component’s initialization. If you move the call into onMount, an event handler or an async function, you do not get an error but something worse – the children simply receive undefined on their later getContext, and the cause is hard to find. The second pitfall concerns reactivity.
graph TD
Provider["Toolbar<br/>setContext('toolbar', …)"]
Group["ButtonGroup<br/>(no props)"]
Divider["Divider<br/>(no props)"]
Consumer["ToolbarButton<br/>getContext('toolbar')"]
Provider --> Group --> Divider --> ConsumerContext is not the same as a store#
Context is bound to the component instance and is not reactive on its own. If I put a plain number into the context and change it later, the children do not update – they read their copy at init, and that is where it stays. A store, in contrast, can be shared globally and is reactive; with $store you subscribe to changes and re-render on every update. I have written in more detail about state outside the component and the store mechanics in Svelte Stores, and the underlying reactivity is the topic of Svelte reactivity.
The two do not exclude each other; on the contrary. The most useful combination in practice puts a store into the context. That gives you both: the implicit distribution through the tree from context and the reactivity of a store.
<!-- ThemeProvider.svelte -->
<script>
import { setContext } from 'svelte';
import { writable } from 'svelte/store';
const theme = writable('light');
setContext('theme', theme);
</script>
<slot></slot>
<!-- ThemeToggle.svelte -->
<script>
import { getContext } from 'svelte';
const theme = getContext('theme');
</script>
<button on:click={() => theme.update((t) => (t === 'light' ? 'dark' : 'light'))}>
Current theme: {$theme}
</button>
Now context passes the store to every descendant component, and because it is a store, {$theme} reacts to every change – without threading a single prop through the tree.
Web Components: framework-neutral reuse#
Slots and context solve composition problems inside a Svelte application. The third tool aims outward. Sometimes a component should also work where no Svelte runs – in an existing page, in another framework, in plain HTML. Svelte can compile a component as a custom element, that is, as a real Web Component according to the browser standard.
You need two things for this. In the component, you assign a tag name via <svelte:options>, and when compiling you enable the customElement option:
<!-- UserBadge.svelte -->
<svelte:options tag="user-badge" />
<script>
export let name = 'Unknown';
export let status = 'offline';
</script>
<span class="badge" data-status={status}>
{name}
</span>
<style>
.badge {
display: inline-flex;
padding: 0.25rem 0.5rem;
border-radius: 999px;
}
.badge[data-status='online'] {
background: #d1fae5;
}
</style>
When bundling, you switch the compiler to custom element output. With Rollup and the official plugin, the relevant part looks like this:
// rollup.config.js
import svelte from 'rollup-plugin-svelte';
export default {
// ...
plugins: [
svelte({
compilerOptions: {
customElement: true,
},
}),
],
};
After that, <user-badge> is a perfectly normal HTML element. You can use it in any page, without any Svelte runtime on the caller’s side:
<script src="./user-badge.js"></script>
<user-badge name="Ada" status="online"></user-badge>
The exported props become element properties and attributes, so you can address the element like any other DOM element. Svelte encapsulates the styles via Shadow DOM – the badge styles do not spill over onto the surrounding page, and page styles do not leak in uncontrolled. That is usually desired, but it surprises you if you expect global styles; :global rules behave differently here.
At this point it is worth taking an honest look at the rough edges, because at the end of 2022, Svelte’s custom element mode is functional but not free of tension. The most important point concerns passing data: HTML attributes are always strings. A name="Ada" in the markup arrives cleanly, but you cannot pass an object or an array as an attribute. You have to set such values as a JavaScript property on the element, such as el.items = [...] – a detail that is easy to overlook if you only use the element declaratively in HTML. Second, custom elements are registered globally once defined; the same tag name cannot be used twice in the same document, which can lead to conflicts when you include several bundles. And third, Shadow DOM encapsulation is a gain for isolation, but it takes away the convenient reach from the outside: if you want to style the element from the page, you have to open the intended places yourself and pass CSS custom properties in deliberately. None of this is a knockout criterion, but these are the places where practice deviates from the first smooth demo.
A practical tip from projects: customElement: true belongs only on the components you actually want to export, not project-wide. Otherwise you compile the whole app into custom elements and lose the regular Svelte component mode with its advantages. In practice, I maintain a separate build entry for this that bundles exactly the components to be exported.
When to use which tool#
The three mechanisms can be sorted clearly by their purpose:
- You choose slots when a component dictates its layout but should get its content from the caller – with slot props also when the caller needs data from the inside for rendering.
- You choose context when a value or a function is needed several levels deeper and prop drilling would burden the intermediate components unnecessarily; for reactive values, you put a store into the context.
- You choose Web Components when a component should run outside the Svelte world – in other frameworks or in plain HTML.
A brief note on context at the end of 2022: throughout, I refer to Svelte 3, the current version these days. The syntax shown, tag="user-badge", is the state of Svelte 3; later versions brought changes at this point that are deliberately left out here. If you keep the repository you work on at Svelte 3, you are on safe ground with everything shown here.
Conclusion#
Slots, context and Web Components seem at first like three unrelated features, but they are a coherent set of composition tools, each with its own direction. Slots pass markup in from the outside and, via slot props, data back out from the inside. Context distributes values implicitly through the component tree and saves you from prop drilling – it only becomes reactive with a store inside. And custom elements lift a component out of the Svelte world so that it runs wherever standard HTML runs. If you briefly ask yourself with every composition problem in which direction content or data should flow and how far it needs to reach, you will reach for the right one of the three tools almost by yourself. This one question saves you most of the detours in a project.
Further reading#
Revised and translated from German with the help of AI.