Component lifecycle hooks, event dispatching, and context management for building interactive Svelte components.
Manage component mounting, updating, and destruction with lifecycle hooks.
/**
* Schedules a callback to run as soon as the component has been mounted to the DOM.
* If a function is returned synchronously, it will be called when the component is unmounted.
* @param fn - Function to run on mount, optionally returning cleanup function
*/
function onMount<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void;
/**
* Schedules a callback to run immediately before the component is unmounted.
* @param fn - Function to run on destroy
*/
function onDestroy(fn: () => any): void;
/**
* Schedules a callback to run immediately before the component is updated after any state change.
* @param fn - Function to run before update
*/
function beforeUpdate(fn: () => any): void;
/**
* Schedules a callback to run immediately after the component has been updated.
* @param fn - Function to run after update
*/
function afterUpdate(fn: () => any): void;Usage Examples:
import { onMount, onDestroy, beforeUpdate, afterUpdate } from "svelte";
// Component mounting
onMount(async () => {
const response = await fetch('/api/data');
const data = await response.json();
// Return cleanup function
return () => {
console.log('Component is being destroyed');
};
});
// Component destruction
onDestroy(() => {
// Cleanup subscriptions, timers, etc.
clearInterval(intervalId);
});
// Before/after updates
let element;
beforeUpdate(() => {
console.log('About to update, current height:', element?.offsetHeight);
});
afterUpdate(() => {
console.log('Updated, new height:', element?.offsetHeight);
});Create and dispatch custom events for component communication.
/**
* Creates an event dispatcher for component events
* @returns EventDispatcher function for dispatching typed events
*/
function createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap>;
interface EventDispatcher<EventMap extends Record<string, any>> {
<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;
}
interface DispatchOptions {
cancelable?: boolean;
}Usage Examples:
import { createEventDispatcher } from "svelte";
// Typed event dispatcher
const dispatch = createEventDispatcher<{
close: never;
submit: { name: string; email: string };
change: string;
}>();
// Dispatching events
function handleClose() {
dispatch('close'); // No detail parameter
}
function handleSubmit() {
dispatch('submit', {
name: 'John',
email: 'john@example.com'
});
}
function handleChange(newValue) {
dispatch('change', newValue, { cancelable: true });
}Share data between components without prop drilling using context.
/**
* Associates a context object with the current component for access by children
* @param key - Context identifier
* @param context - Value to store in context
* @returns The context value
*/
function setContext<T>(key: any, context: T): T;
/**
* Retrieves context that belongs to the closest parent component with the specified key
* @param key - Context identifier
* @returns The context value
*/
function getContext<T>(key: any): T;
/**
* Retrieves the whole context map from the closest parent component
* @returns Map of all context values
*/
function getAllContexts<T extends Map<any, any> = Map<any, any>>(): T;
/**
* Checks whether a given key has been set in the context of a parent component
* @param key - Context identifier to check
* @returns True if context exists
*/
function hasContext(key: any): boolean;Usage Examples:
import { setContext, getContext, hasContext } from "svelte";
// Parent component - setting context
const themeKey = Symbol('theme');
setContext(themeKey, {
primaryColor: '#007acc',
backgroundColor: '#ffffff'
});
// Child component - consuming context
const theme = getContext(themeKey);
// Conditional context usage
if (hasContext(themeKey)) {
const theme = getContext(themeKey);
console.log('Theme available:', theme);
}
// Getting all contexts
const allContexts = getAllContexts();
console.log('Available contexts:', allContexts);Control when Svelte updates the DOM and flushes pending changes.
/**
* Returns a promise that resolves once pending state changes have been applied
* @returns Promise that resolves after DOM updates
*/
function tick(): Promise<void>;Usage Examples:
import { tick } from "svelte";
let items = [];
let container;
async function addItem() {
items = [...items, { id: Date.now(), text: 'New item' }];
// Wait for DOM to update
await tick();
// Now we can access the updated DOM
const newElement = container.lastElementChild;
newElement.scrollIntoView();
}
// Useful for animations or DOM measurements after state changes
async function animateHeight() {
const startHeight = element.offsetHeight;
showContent = true;
await tick(); // Wait for content to render
const endHeight = element.offsetHeight;
// Now animate from startHeight to endHeight
}/**
* Base class for Svelte components with TypeScript support
*/
class SvelteComponent<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any> {
constructor(options: ComponentConstructorOptions<Props>);
/** Destroy the component and cleanup resources */
$destroy(): void;
/** Listen to component events */
$on<K extends Extract<keyof Events, string>>(
type: K,
callback: ((e: Events[K]) => void) | null | undefined
): () => void;
/** Update component props */
$set(props: Partial<Props>): void;
}
interface ComponentConstructorOptions<Props extends Record<string, any> = Record<string, any>> {
/** Target DOM element to mount the component */
target: Element | Document | ShadowRoot;
/** Element to insert the component before */
anchor?: Element;
/** Initial props for the component */
props?: Props;
/** Context map for the component */
context?: Map<any, any>;
/** Whether to hydrate existing DOM */
hydrate?: boolean;
/** Whether to play intro transitions */
intro?: boolean;
}