useDefaults
Resolves a component's defaultable props against the nearest DefaultsProvider.
Signature
import { useDefaults } from 'sveltier';
function useDefaults<T extends object>(
name: string,
builtins: T
): (local: Partial<T>) => T;Call it during component initialisation; it reads the provider context once. The resolver it
returns is pure, so call it inside $derived to track both the props and the provider's
defaults.
Parameters and result
| Name | Type | Description |
|---|---|---|
name | string | The component’s key in DefaultsConfig and ComponentDefaults, for example "PriceTag". |
builtins | T | Every defaultable prop with its built-in value. Only these keys are resolved, so global defaults never add a prop the component does not have. |
returns | (local: Partial<T>) => T | A pure resolver. Call it inside $derived with the props as passed; undefined and null mean "not set". |
Example
<script lang="ts">
import { useDefaults, type Color, type ComponentDefaults, type Size } from 'sveltier';
interface Props {
value: number;
size?: Size;
color?: Color;
showSign?: boolean;
}
// No fallbacks in the destructuring: a fallback would hide the provider's defaults.
let { value, size, color, showSign }: Props = $props();
const resolve = useDefaults<ComponentDefaults['PriceTag']>('PriceTag', {
size: 'md',
color: 'neutral',
showSign: true
});
const p = $derived(resolve({ size, color, showSign }));
</script>
<span class="price-tag price-tag--{p.size}">
{p.showSign && value > 0 ? '+' : ''}{value}
</span>Pass the type registered in ComponentDefaults as T to keep literal
types such as Size. See Defaults.