What are Svelte 5 snippets and how do they replace slots?

Answer

Snippets are Svelte 5's replacement for slots, offering more flexibility. They are reusable chunks of template that can be passed to components or used locally. Defining a snippet: {#snippet header(title)} <h1>{title}</h1> {/snippet}. Rendering a snippet: {@render header('My Title')}. Passing snippets to components: snippets defined in a parent's scope can be passed as props: <Table {header} {row} {footer} />. Inside the Table component: let { header, row, footer } = $props(); {@render header()}. Improvements over slots: Parameters: snippets can accept arguments (like render props in React). Portability: snippets can be passed to any component, not just the direct parent. Default snippets: the content between component tags is the default snippet: <Component>This is the default snippet</Component>, accessed as children prop. Conditional rendering: {#if children} {@render children()} {/if}. Snippets make component APIs more explicit and flexible than slots.