The svelte
package exposes lifecycle functions and the context API.
onMountpermalink
ts
function onMount<T>(fn: () =>| NotFunction<T>| Promise<NotFunction<T>>| (() => any)): void;
The onMount
function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component's initialisation (but doesn't need to live inside the component; it can be called from an external module).
onMount
does not run inside a server-side component.
<script>
import { onMount } from 'svelte';
onMount(() => {
console.log('the component has mounted');
});
</script>
If a function is returned from onMount
, it will be called when the component is unmounted.
<script>
import { onMount } from 'svelte';
onMount(() => {
const interval = setInterval(() => {
console.log('beep');
}, 1000);
return () => clearInterval(interval);
});
</script>
This behaviour will only work when the function passed to
onMount
synchronously returns a value.async
functions always return aPromise
, and as such cannot synchronously return a function.
beforeUpdatepermalink
ts
function beforeUpdate(fn: () => void): void;
Schedules a callback to run immediately before the component is updated after any state change.
The first time the callback runs will be before the initial
onMount
<script>
import { beforeUpdate } from 'svelte';
beforeUpdate(() => {
console.log('the component is about to update');
});
</script>
afterUpdatepermalink
ts
function afterUpdate(fn: () => void): void;
Schedules a callback to run immediately after the component has been updated.
The first time the callback runs will be after the initial
onMount
<script>
import { afterUpdate } from 'svelte';
afterUpdate(() => {
console.log('the component just updated');
});
</script>
onDestroypermalink
ts
function onDestroy(fn: () => any): void;
Schedules a callback to run immediately before the component is unmounted.
Out of onMount
, beforeUpdate
, afterUpdate
and onDestroy
, this is the only one that runs inside a server-side component.
<script>
import { onDestroy } from 'svelte';
onDestroy(() => {
console.log('the component is being destroyed');
});
</script>
tickpermalink
ts
function tick(): Promise<void>;
Returns a promise that resolves once any pending state changes have been applied, or in the next microtask if there are none.
<script>
import { beforeUpdate, tick } from 'svelte';
beforeUpdate(async () => {
console.log('the component is about to update');
await tick();
console.log('the component just updated');
});
</script>
setContextpermalink
ts
function setContext<T>(key: any, context: T): T;
Associates an arbitrary context
object with the current component and the specified key
and returns that object. The context is then available to children of the component (including slotted content) with getContext
.
Like lifecycle functions, this must be called during component initialisation.
<script>
import { setContext } from 'svelte';
setContext('answer', 42);
</script>
Context is not inherently reactive. If you need reactive values in context then you can pass a store into context, which will be reactive.
getContextpermalink
ts
function getContext<T>(key: any): T;
Retrieves the context that belongs to the closest parent component with the specified key
. Must be called during component initialisation.
<script>
import { getContext } from 'svelte';
const answer = getContext('answer');
</script>
hasContextpermalink
ts
function hasContext(key: any): boolean;
Checks whether a given key
has been set in the context of a parent component. Must be called during component initialisation.
<script>
import { hasContext } from 'svelte';
if (hasContext('answer')) {
// do something
}
</script>
getAllContextspermalink
ts
function getAllContexts<T extends Map<any, any> = Map<any, any>>(): T;
Retrieves the whole context map that belongs to the closest parent component. Must be called during component initialisation. Useful, for example, if you programmatically create a component and want to pass the existing context to it.
<script>
import { getAllContexts } from 'svelte';
const contexts = getAllContexts();
</script>
createEventDispatcherpermalink
ts
function createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap>;
Creates an event dispatcher that can be used to dispatch component events. Event dispatchers are functions that can take two arguments: name
and detail
.
Component events created with createEventDispatcher
create a CustomEvent. These events do not bubble. The detail
argument corresponds to the CustomEvent.detail property and can contain any type of data.
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
</script>
<button on:click={() => dispatch('notify', 'detail value')}>Fire Event</button>
Events dispatched from child components can be listened to in their parent. Any data provided when the event was dispatched is available on the detail
property of the event object.
<script>
function callbackFunction(event) {
console.log(`Notify fired! Detail: ${event.detail}`);
}
</script>
<Child on:notify={callbackFunction} />
Events can be cancelable by passing a third parameter to the dispatch function. The function returns false
if the event is cancelled with event.preventDefault()
, otherwise it returns true
.
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function notify() {
const shouldContinue = dispatch('notify', 'detail value', { cancelable: true });
if (shouldContinue) {
// no one called preventDefault
} else {
// a listener called preventDefault
}
}
</script>
You can type the event dispatcher to define which events it can receive. This will make your code more type safe both within the component (wrong calls are flagged) and when using the component (types of the events are now narrowed). See here how to do it.
Typespermalink
ComponentConstructorOptionspermalink
Svelte components were classes in Svelte 4. In Svelte 5, thy are not anymore. Use
mount
orcreateRoot
instead to instantiate components. See breaking changes for more info.
ts
interface ComponentConstructorOptions<Props extends Record<string, any> = Record<string, any>> {…}
ts
target: Element | Document | ShadowRoot;
ts
anchor?: Element;
ts
props?: Props;
ts
context?: Map<any, any>;
ts
hydrate?: boolean;
ts
intro?: boolean;
ts
$$inline?: boolean;
ComponentEventspermalink
Convenience type to get the events the given component expects. Example:
<script lang="ts">
import type { ComponentEvents } from 'svelte';
import Component from './Component.svelte';
function handleCloseEvent(event: ComponentEvents<Component>['close']) {
console.log(event.detail);
}
</script>
<Component on:close={handleCloseEvent} />
ts
type ComponentEvents<Comp extends SvelteComponent> =Comp extends SvelteComponent<any, infer Events>? Events: never;
ComponentPropspermalink
Convenience type to get the props the given component expects. Example:
<script lang="ts">
import type { ComponentProps } from 'svelte';
import Component from './Component.svelte';
const props: ComponentProps<Component> = { foo: 'bar' }; // Errors if these aren't the correct props
</script>
ts
type ComponentProps<Comp extends SvelteComponent> =Comp extends SvelteComponent<infer Props> ? Props : never;
ComponentTypepermalink
Convenience type to get the type of a Svelte component. Useful for example in combination with
dynamic components using <svelte:component>
.
Example:
<script lang="ts">
import type { ComponentType, SvelteComponent } from 'svelte';
import Component1 from './Component1.svelte';
import Component2 from './Component2.svelte';
const component: ComponentType = someLogic() ? Component1 : Component2;
const componentOfCertainSubType: ComponentType<SvelteComponent<{ needsThisProp: string }>> = someLogic() ? Component1 : Component2;
</script>
<svelte:component this={component} />
<svelte:component this={componentOfCertainSubType} needsThisProp="hello" />
ts
type ComponentType<Comp extends SvelteComponent> = (new (options: ComponentConstructorOptions<Comp extends SvelteComponent<infer Props>? Props: Record<string, any>>) => Comp) & {/** The custom element version of the component. Only present if compiled with the `customElement` compiler option */element?: typeof HTMLElement;};
EventDispatcherpermalink
ts
interface EventDispatcher<EventMap extends Record<string, any>> {…}
ts
<Type extends keyof EventMap>(...args: null extends EventMap[Type]? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]: undefined extends EventMap[Type]? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]: [type: Type, parameter: EventMap[Type], options?: DispatchOptions]): boolean;
Snippetpermalink
The type of a #snippet
block. You can use it to (for example) express that your component expects a snippet of a certain type:
ts
let {banner } =$props <{banner :Snippet <{text : string }> }>();
You can only call a snippet through the {@render ...}
tag.
ts
interface Snippet<T = void> {…}
ts
(arg: T): typeof SnippetReturn & {_: 'functions passed to {@render ...} tags must use the `Snippet` type imported from "svelte"';};
SvelteComponentpermalink
Can be used to create strongly typed Svelte components.
Example:permalink
You have component library on npm called component-library
, from which
you export a component called MyComponent
. For Svelte+TypeScript users,
you want to provide typings. Therefore you create a index.d.ts
:
ts
import {SvelteComponent } from "svelte";export classMyComponent extendsSvelteComponent <{foo : string}> {}
Typing this makes it possible for IDEs like VS Code with the Svelte extension to provide intellisense and to use the component like this in a Svelte file with TypeScript:
<script lang="ts">
import { MyComponent } from "component-library";
</script>
<MyComponent foo={'bar'} />
This was the base class for Svelte components in Svelte 4. Svelte 5+ components
are completely different under the hood. You should only use this type for typing,
not actually instantiate components with new
- use mount
or createRoot
instead.
See breaking changes
for more info.
ts
class SvelteComponent<Props extends Record<string, any> = any,Events extends Record<string, any> = any,Slots extends Record<string, any> = any> {…}
ts
[prop: string]: any;
ts
constructor(options: ComponentConstructorOptions<PropsWithChildren<Props, Slots>>);
- deprecated This constructor only exists when using the
asClassComponent
compatibility helper, which is a stop-gap solution. Migrate towards usingmount
orcreateRoot
instead. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes for more info.
ts
$destroy(): void;
- deprecated This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes for more info.
ts
$on<K extends Extract<keyof Events, string>>(type: K,callback: (e: Events[K]) => void): () => void;
- deprecated This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes for more info.
ts
$set(props: Partial<Props>): void;
- deprecated This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes for more info.
SvelteComponentTypedpermalink
Use
SvelteComponent
instead. See TODO for more information.
ts
class SvelteComponentTyped<Props extends Record<string, any> = any,Events extends Record<string, any> = any,Slots extends Record<string, any> = any> extends SvelteComponent<Props, Events, Slots> {}