Svelte 96 ๐งก Headless Component Design Patterns with Svelte Runes and Snippets
Svelte 5 has introduced a fundamental paradigm shift in how we manage state and interactivity through Runes. While previous versions of Svelte relied heavily on component-level state and proprietary slot mechanics, the introduction of $state, $derived, and $effect allows for a more functional, decoupled approach. Headless component designโthe practice of building components that provide logic and accessibility without dictating the visual presentationโhas become significantly more powerful and cleaner under this new reactivity model.
This chapter explores how to leverage Runes to encapsulate complex behaviors, such as state-driven UI patterns, into reusable logic units. We will move beyond the traditional “component as a unit” approach toward “logic as a service,” using Snippets to render the custom UI provided by the consumer. We will cover the core headless philosophy, the implementation of stateful logic, and the bridge between logic and presentation.
Key point: Headless components in Svelte 5 leverage Runes to isolate stateful logic from markup, allowing the consumer of the component to define the visual representation through Snippets, effectively separating concerns between behavior and design.
Why exists
The separation of logic and presentation problem. UI frameworks often couple behavior and styling, making it difficult to maintain design systems that need to look different across various parts of an application while keeping the same underlying interaction model.
The styling constraint problem. When a component comes with “built-in” CSS, overriding that styling often requires !important tags or complex CSS specificity wars. Headless components exist to provide the functionality without any default style injection.
The testing overhead problem. Testing UI components that have heavy internal markup is difficult and brittle. Testing logic that is extracted into pure Runes-based functions or classes is trivial and allows for granular unit testing without rendering the DOM.
The accessibility maintenance problem. Implementing complex patterns like ARIA-compliant dropdowns or carousels is hard. By providing a headless logic layer that manages focus and keyboard events, developers can bake accessibility into the logic and reuse it across multiple projects.
The composition limitations of legacy slots. Older Svelte slots were often insufficient for complex configuration, sometimes requiring multiple named slots or complex prop-passing. Snippets provide a more flexible, render-function-like approach to injecting UI into a component.
The reactivity leakage problem. In legacy Svelte, state was tied to the component lifecycle. If you wanted to move state to a helper file, it was difficult to maintain reactivity. Runes allow state to live anywhere, making “Headless logic” a first-class citizen of the codebase.
a. The Headless Philosophy
The headless pattern treats a component as two distinct entities: the “Logic Provider” and the “UI Consumer.” The Logic Provider manages the state, events, and lifecycle calculations using Svelte Runes. It does not contain any HTML elements that dictate the appearance of the UI. Instead, it exposes an object or class interface that the consumer can use to render their own markup.
// use-toggle.svelte.ts
export function useToggle(initial = false) {
let value = $state(initial);
return {
get value() { return value; },
toggle: () => { value = !value; },
set: (v: boolean) => { value = v; }
};
}
In this example, the useToggle function is the logic layer. It encapsulates the reactive state. The consuming component is entirely responsible for what the user sees, while the logic layer guarantees the correctness of the toggle state transition.
This shift moves away from a component that tries to do everything. By moving logic into a .svelte.ts file, you create a system where the logic can be imported, tested, and shared across different componentsโeven ones that have entirely different visual needs or frameworks requirements in the future.
b. Implementing Headless State with Runes
Runes like $state and $derived allow us to build complex machines that track internal state transitions. In a headless component, you might have a set of internal properties that should not be exposed directly to the consumer to prevent accidental modification, but the consumer needs a way to react to those changes.
// use-counter.svelte.ts
export function useCounter(max: number) {
let count = $state(0);
let isMax = $derived(count >= max);
return {
get count() { return count; },
get isMax() { return isMax; },
increment: () => { if (count < max) count++; },
reset: () => { count = 0; }
};
}
Using getters in the returned object is a common pattern to ensure that the internal state remains readonly from the perspective of the consumer, while still allowing the consumer to react to the state when it changes. Because $derived is used, the isMax property will automatically re-evaluate when count changes, and the consuming component will re-render exactly when needed.
This provides an “encapsulation layer.” The consumer doesn’t need to know how isMax is calculated, only that it is a boolean property that updates reactively. This prevents the “leaky abstraction” where consumers have to know the internal data structure of your component.
c. Exposing Logic via Snippets
Snippets allow you to pass fragments of UI into a component. This is the “Consumer” side of the headless pattern. You pass a snippet to the component, and the component invokes the snippet, injecting the logic results as props.
<!-- CounterView.svelte -->
<script>
let { children, logic } = $props();
</script>
<div class="wrapper">
{@render children(logic)}
</div>
The logic object represents the API provided by our useCounter function. The consumer provides the template:
<CounterView logic={useCounter(10)} let:logic>
<button onclick={logic.increment}>
Count: {logic.count} {logic.isMax ? "(Maxed!)" : ""}
</button>
</CounterView>
This effectively decouples the “how” (logic) from the “what” (appearance). You can swap out the button for an anchor tag, a custom stylized div, or an icon-based button without ever touching the logic code. The children snippet acts as a render prop, receiving the reactive state and methods to trigger interactivity.
Complete Example Session
// ============================================
// PART 1: LOGIC PROVIDER
// ============================================
// tabs.svelte.ts
export function useTabs(initialIndex = 0) {
let activeIndex = $state(initialIndex);
return {
get activeIndex() { return activeIndex; },
select: (index: number) => { activeIndex = index; },
isActive: (index: number) => activeIndex === index
};
}
// ============================================
// PART 2: THE HEADLESS COMPONENT WRAPPER
// ============================================
// TabsContainer.svelte
<script>
let { logic, children, buttons } = $props();
</script>
<div class="tabs-header">
{@render buttons(logic)}
</div>
<div class="tabs-content">
{@render children(logic)}
</div>
// ============================================
// PART 3: CONSUMER IMPLEMENTATION
// ============================================
<script>
const tabs = useTabs(0);
</script>
<TabsContainer logic={tabs}
buttons={(logic) => (
<button onclick={() => logic.select(0)}>Tab 1</button>
<button onclick={() => logic.select(1)}>Tab 2</button>
)}
children={(logic) => (
<div>
{logic.isActive(0) ? "Content 1" : "Content 2"}
</div>
)}
/>
This three-part session demonstrates the logic isolation of useTabs, the container wrapper that provides layout structure, and the consumer implementation that injects custom UI.
Quick Reference
Reactive Logic Patterns
| Pattern | Goal | Implementation |
|---|---|---|
| Getter exposure | Read-only access | get prop() { return state; } |
| Computed values | Efficient derived state | $derived(expression) |
| Event handlers | Encapsulated mutation | () => { state = val; } |
Snippet Injection
| Feature | Svelte 5 Syntax | Purpose |
|---|---|---|
| Passing data | {@render children(data)} | Injects state into UI |
| Destructuring | let: { value } = children | Clean property access |
| Fallbacks | children ?? fallback | Conditional UI |
State Ownership
| Model | Ownership |
|---|---|
| Headless | Logic provider |
| UI | Consumer (via Snippets) |
| Props | Config (passed into Logic) |
Best Practices
โ Do This:
// Expose state as getters to prevent external mutation
get count() { return count; } // โ
// Extract logic into pure .svelte.ts files
export function useFeature() { ... } // โ
// Use snippets for flexible UI injection
{@render children(logic)} // โ
// Use derived state for computed dependencies
const isInvalid = $derived(value < 0); // โ
โ Don’t Do This:
// Don't expose mutable state objects directly
return { count }; // โ
// Don't mix logic and markup in one file
<script> ... </script> <div> ... </div> // โ
// Don't use legacy slots for complex logic injection
<slot name="header" /> // โ
// Don't duplicate logic across different components
// (Use a shared Rune instead) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Over-fragmentation | Trying to be “too headless” | Keep related logic together |
| Reactivity loss | Destructuring state too early | Use getters/proxy objects |
| Prop drilling | Passing logic through too many levels | Use Context API |
| Logic bloat | Adding presentation logic to hooks | Keep hooks purely behavioral |
Real-World Examples
1. Accessible Accordion logic
let isOpen = $state(false);
const toggle = () => isOpen = !isOpen;
2. Pagination state
let page = $state(1);
const next = () => page++;
3. Form validation
let error = $derived(value.length < 3 ? "Too short" : null);
4. Dropdown focus manager
let focused = $state(false);
const onFocus = () => focused = true;
5. Search filtering
let filtered = $derived(items.filter(i => i.includes(query)));
6. Clipboard copy handler
const copy = (val) => navigator.clipboard.writeText(val);
7. Dark mode toggler
let theme = $state('light');
const toggle = () => theme = theme === 'light' ? 'dark' : 'light';
8. Timer / Counter
let time = $state(0);
const start = () => setInterval(() => time++, 1000);
9. Drag and drop state
let dragging = $state(false);
const setDragging = (val) => dragging = val;
10. Multi-step wizard
let step = $state(1);
const next = () => step++;
Visual
The Headless Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CONSUMER (UI) โ
โ โโโ Snippet A (Button) โ
โ โโโ Snippet B (Display) โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ LOGIC PROVIDER (Rune) โ โ
โ โ โโโ State ($state) โ โ
โ โ โโโ Computed ($derived) โ โ
โ โ โโโ Methods โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
State Lifecycle and Reactivity
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ [Source] โ $state() โ
โ โ โ
โ โผ โ
โ [Transform] โ $derived() โ
โ โ โ
โ โผ โ
โ [Consumption] โ Snippet โ
โ โ โ
โ โผ โ
โ [Browser] โ Render DOM โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Logic vs UI Separation
โโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ
โ LOGIC (.svelte.ts) โ โ UI (.svelte) โ
โ โโโโโโโโโโโโโโโโโโโโ โ โ โโโโโโโโโโโโโโโโโโโโ โ
โ โ state variables โ โ โ โ snippet layout โ โ
โ โ event methods โ โ โ โ event bindings โ โ
โ โโโโโโโโโโโโโโโโโโโโ โ โ โโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโฌโโโโโโโโโโโโ โโโโโโโโโโโโฒโโโโโโโโโโโโ
โโโโโโโ injected via โโโโโโ
interface
Summary
| Item | Value |
|---|---|
| Logic base | .svelte.ts files |
| State | $state |
| Computed | $derived |
| UI Injection | {@render} |
| Pattern | Headless |
| Responsibility | Logic = Logic, UI = Snippets |
| State access | Getters |
Key takeaways:
- Headless design decouples. Logic lives in Runes, while presentation lives in Snippets, allowing for massive design flexibility.
- Runes as the “Logic Layer.” Using
.svelte.tsfiles for logic ensures state and business rules remain independent of DOM structure. - Getters for encapsulation. Exposing state through getters protects internal variables while maintaining reactivity for consumers.
- Snippets as render props. The
{@render}pattern allows passing components as dynamic UI fragments into the logic-driven container. - Reusability and Testing. Headless logic is easier to test because it doesn’t require a DOM environment to verify its state transitions.
- Context for deep structures. Use Context API if logic needs to be accessed by deeply nested components without manual prop drilling.
Remember: Headless component design is about building the “interaction machine” without building the “visual skin.” By leveraging Svelte 5 Runes for logic and Snippets for layout, you create a robust, maintainable system where logic can survive complete visual re-designs. Always prefer explicit interfaces and getters to keep your state predictable and your UI consumers decoupled from your implementation details.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!