| | |

Svelte 96 ๐Ÿงก Headless Component Design Patterns with Svelte Runes and Snippets

โฑ๏ธ Estimated read: 9 min | |

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

PatternGoalImplementation
Getter exposureRead-only accessget prop() { return state; }
Computed valuesEfficient derived state$derived(expression)
Event handlersEncapsulated mutation() => { state = val; }

Snippet Injection

FeatureSvelte 5 SyntaxPurpose
Passing data{@render children(data)}Injects state into UI
Destructuringlet: { value } = childrenClean property access
Fallbackschildren ?? fallbackConditional UI

State Ownership

ModelOwnership
HeadlessLogic provider
UIConsumer (via Snippets)
PropsConfig (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

PitfallWhy It HappensFix
Over-fragmentationTrying to be “too headless”Keep related logic together
Reactivity lossDestructuring state too earlyUse getters/proxy objects
Prop drillingPassing logic through too many levelsUse Context API
Logic bloatAdding presentation logic to hooksKeep 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

ItemValue
Logic base.svelte.ts files
State$state
Computed$derived
UI Injection{@render}
PatternHeadless
ResponsibilityLogic = Logic, UI = Snippets
State accessGetters

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.ts files 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.

Was this helpful?


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!