Svelte โ€ข Reference

svelte/reactivity

On this page

Svelte provides reactive versions of various built-ins like Map, Set and URL that can be used just like their native counterparts, as well as a handful of additional utilities for handling reactivity.

import {
	function createSubscriber(start: (update: () => void) => (() => void) | void): () => void

Returns a subscribe function that integrates external event-based systems with Svelte's reactivity. It's particularly useful for integrating with web APIs like MediaQuery, IntersectionObserver, or WebSocket.

If subscribe is called inside an effect (including indirectly, for example inside a getter), the start callback will be called with an update function. Whenever update is called, the effect re-runs.

If start returns a cleanup function, it will be called when the effect is destroyed.

If subscribe is called in multiple effects, start will only be called once as long as the effects are active, and the returned teardown function will only be called when all effects are destroyed.

It's best understood with an example. Here's an implementation of MediaQuery:

import { createSubscriber } from 'svelte/reactivity';
import { on } from 'svelte/events';

export class MediaQuery {
	#query;
	#subscribe;

	constructor(query) {
		this.#query = window.matchMedia(`(${query})`);

		this.#subscribe = createSubscriber((update) => {
			// when the `change` event occurs, re-run any effects that read `this.current`
			const off = on(this.#query, 'change', update);

			// stop listening when all the effects are destroyed
			return () => off();
		});
	}

	get current() {
		// This makes the getter reactive, if read in an effect
		this.#subscribe();

		// Return the current state of the query, whether or not we're in an effect
		return this.#query.matches;
	}
}
@since5.7.0
function createSubscriber(start: (update: () => void) => (() => void) | void): () => void

Returns a subscribe function that integrates external event-based systems with Svelte's reactivity. It's particularly useful for integrating with web APIs like MediaQuery, IntersectionObserver, or WebSocket.

If subscribe is called inside an effect (including indirectly, for example inside a getter), the start callback will be called with an update function. Whenever update is called, the effect re-runs.

If start returns a cleanup function, it will be called when the effect is destroyed.

If subscribe is called in multiple effects, start will only be called once as long as the effects are active, and the returned teardown function will only be called when all effects are destroyed.

It's best understood with an example. Here's an implementation of MediaQuery:

import { createSubscriber } from 'svelte/reactivity';
import { on } from 'svelte/events';

export class MediaQuery {
	#query;
	#subscribe;

	constructor(query) {
		this.#query = window.matchMedia(`(${query})`);

		this.#subscribe = createSubscriber((update) => {
			// when the `change` event occurs, re-run any effects that read `this.current`
			const off = on(this.#query, 'change', update);

			// stop listening when all the effects are destroyed
			return () => off();
		});
	}

	get current() {
		// This makes the getter reactive, if read in an effect
		this.#subscribe();

		// Return the current state of the query, whether or not we're in an effect
		return this.#query.matches;
	}
}
@since5.7.0
createSubscriber
,
class MediaQuery

Creates a media query and provides a current property that reflects whether or not it matches.

Use it carefully โ€” during server-side rendering, there is no way to know what the correct value should be, potentially causing content to change upon hydration. If you can use the media query in CSS to achieve the same effect, do that.

<script>
	import { MediaQuery } from 'svelte/reactivity';

	const large = new MediaQuery('min-width: 800px');
</script>

<h1>{large.current ? 'large screen' : 'small screen'}</h1>
@extendsReactiveValue<boolean> *@since5.7.0
class MediaQuery

Creates a media query and provides a current property that reflects whether or not it matches.

Use it carefully โ€” during server-side rendering, there is no way to know what the correct value should be, potentially causing content to change upon hydration. If you can use the media query in CSS to achieve the same effect, do that.

<script>
	import { MediaQuery } from 'svelte/reactivity';

	const large = new MediaQuery('min-width: 800px');
</script>

<h1>{large.current ? 'large screen' : 'small screen'}</h1>
@extendsReactiveValue<boolean> *@since5.7.0
MediaQuery
,
class SvelteDate

A reactive version of the built-in Date object. Reading the date (whether with methods like date.getTime() or date.toString(), or via things like Intl.DateTimeFormat) in an effect or derived will cause it to be re-evaluated when the value of the date changes.

<script>
	import { SvelteDate } from 'svelte/reactivity';

	const date = new SvelteDate();

	const formatter = new Intl.DateTimeFormat(undefined, {
	  hour: 'numeric',
	  minute: 'numeric',
	  second: 'numeric'
	});

	$effect(() => {
		const interval = setInterval(() => {
			date.setTime(Date.now());
		}, 1000);

		return () => {
			clearInterval(interval);
		};
	});
</script>

<p>The time is {formatter.format(date)}</p>
class SvelteDate

A reactive version of the built-in Date object. Reading the date (whether with methods like date.getTime() or date.toString(), or via things like Intl.DateTimeFormat) in an effect or derived will cause it to be re-evaluated when the value of the date changes.

<script>
	import { SvelteDate } from 'svelte/reactivity';

	const date = new SvelteDate();

	const formatter = new Intl.DateTimeFormat(undefined, {
	  hour: 'numeric',
	  minute: 'numeric',
	  second: 'numeric'
	});

	$effect(() => {
		const interval = setInterval(() => {
			date.setTime(Date.now());
		}, 1000);

		return () => {
			clearInterval(interval);
		};
	});
</script>

<p>The time is {formatter.format(date)}</p>
SvelteDate
,
class SvelteMap<K, V>

A reactive version of the built-in Map object. Reading contents of the map (by iterating, or by reading map.size or calling map.get(...) or map.has(...) as in the tic-tac-toe example below) in an effect or derived will cause it to be re-evaluated as necessary when the map is updated.

Note that values in a reactive map are not made deeply reactive.

<script>
	import { SvelteMap } from 'svelte/reactivity';
	import { result } from './game.js';

	let board = new SvelteMap();
	let player = $state('x');
	let winner = $derived(result(board));

	function reset() {
		player = 'x';
		board.clear();
	}
</script>

<div class="board">
	{#each Array(9), i}
		<button
			disabled={board.has(i) || winner}
			onclick={() => {
				board.set(i, player);
				player = player === 'x' ? 'o' : 'x';
			}}
		>{board.get(i)}</button>
	{/each}
</div>

{#if winner}
	<p>{winner} wins!</p>
	<button onclick={reset}>reset</button>
{:else}
	<p>{player} is next</p>
{/if}
class SvelteMap<K, V>

A reactive version of the built-in Map object. Reading contents of the map (by iterating, or by reading map.size or calling map.get(...) or map.has(...) as in the tic-tac-toe example below) in an effect or derived will cause it to be re-evaluated as necessary when the map is updated.

Note that values in a reactive map are not made deeply reactive.

<script>
	import { SvelteMap } from 'svelte/reactivity';
	import { result } from './game.js';

	let board = new SvelteMap();
	let player = $state('x');
	let winner = $derived(result(board));

	function reset() {
		player = 'x';
		board.clear();
	}
</script>

<div class="board">
	{#each Array(9), i}
		<button
			disabled={board.has(i) || winner}
			onclick={() => {
				board.set(i, player);
				player = player === 'x' ? 'o' : 'x';
			}}
		>{board.get(i)}</button>
	{/each}
</div>

{#if winner}
	<p>{winner} wins!</p>
	<button onclick={reset}>reset</button>
{:else}
	<p>{player} is next</p>
{/if}
SvelteMap
,
class SvelteSet<T>

A reactive version of the built-in Set object. Reading contents of the set (by iterating, or by reading set.size or calling set.has(...) as in the example below) in an effect or derived will cause it to be re-evaluated as necessary when the set is updated.

Note that values in a reactive set are not made deeply reactive.

<script>
	import { SvelteSet } from 'svelte/reactivity';
	let monkeys = new SvelteSet();

	function toggle(monkey) {
		if (monkeys.has(monkey)) {
			monkeys.delete(monkey);
		} else {
			monkeys.add(monkey);
		}
	}
</script>

{#each ['๐Ÿ™ˆ', '๐Ÿ™‰', '๐Ÿ™Š'] as monkey}
	<button onclick={() => toggle(monkey)}>{monkey}</button>
{/each}

<button onclick={() => monkeys.clear()}>clear</button>

{#if monkeys.has('๐Ÿ™ˆ')}<p>see no evil</p>{/if}
{#if monkeys.has('๐Ÿ™‰')}<p>hear no evil</p>{/if}
{#if monkeys.has('๐Ÿ™Š')}<p>speak no evil</p>{/if}
class SvelteSet<T>

A reactive version of the built-in Set object. Reading contents of the set (by iterating, or by reading set.size or calling set.has(...) as in the example below) in an effect or derived will cause it to be re-evaluated as necessary when the set is updated.

Note that values in a reactive set are not made deeply reactive.

<script>
	import { SvelteSet } from 'svelte/reactivity';
	let monkeys = new SvelteSet();

	function toggle(monkey) {
		if (monkeys.has(monkey)) {
			monkeys.delete(monkey);
		} else {
			monkeys.add(monkey);
		}
	}
</script>

{#each ['๐Ÿ™ˆ', '๐Ÿ™‰', '๐Ÿ™Š'] as monkey}
	<button onclick={() => toggle(monkey)}>{monkey}</button>
{/each}

<button onclick={() => monkeys.clear()}>clear</button>

{#if monkeys.has('๐Ÿ™ˆ')}<p>see no evil</p>{/if}
{#if monkeys.has('๐Ÿ™‰')}<p>hear no evil</p>{/if}
{#if monkeys.has('๐Ÿ™Š')}<p>speak no evil</p>{/if}
SvelteSet
,
class SvelteURL

A reactive version of the built-in URL object. Reading properties of the URL (such as url.href or url.pathname) in an effect or derived will cause it to be re-evaluated as necessary when the URL changes.

The searchParams property is an instance of SvelteURLSearchParams.

Example:

<script>
	import { SvelteURL } from 'svelte/reactivity';

	const url = new SvelteURL('https://example.com/path');
</script>

<!-- changes to these... -->
<input bind:value={url.protocol} />
<input bind:value={url.hostname} />
<input bind:value={url.pathname} />

<hr />

<!-- will update `href` and vice versa -->
<input bind:value={url.href} size="65" />
class SvelteURL

A reactive version of the built-in URL object. Reading properties of the URL (such as url.href or url.pathname) in an effect or derived will cause it to be re-evaluated as necessary when the URL changes.

The searchParams property is an instance of SvelteURLSearchParams.

Example:

<script>
	import { SvelteURL } from 'svelte/reactivity';

	const url = new SvelteURL('https://example.com/path');
</script>

<!-- changes to these... -->
<input bind:value={url.protocol} />
<input bind:value={url.hostname} />
<input bind:value={url.pathname} />

<hr />

<!-- will update `href` and vice versa -->
<input bind:value={url.href} size="65" />
SvelteURL
,
class SvelteURLSearchParams

A reactive version of the built-in URLSearchParams object. Reading its contents (by iterating, or by calling params.get(...) or params.getAll(...) as in the example below) in an effect or derived will cause it to be re-evaluated as necessary when the params are updated.

<script>
	import { SvelteURLSearchParams } from 'svelte/reactivity';

	const params = new SvelteURLSearchParams('message=hello');

	let key = $state('key');
	let value = $state('value');
</script>

<input bind:value={key} />
<input bind:value={value} />
<button onclick={() => params.append(key, value)}>append</button>

<p>?{params.toString()}</p>

{#each params as [key, value]}
	<p>{key}: {value}</p>
{/each}
class SvelteURLSearchParams

A reactive version of the built-in URLSearchParams object. Reading its contents (by iterating, or by calling params.get(...) or params.getAll(...) as in the example below) in an effect or derived will cause it to be re-evaluated as necessary when the params are updated.

<script>
	import { SvelteURLSearchParams } from 'svelte/reactivity';

	const params = new SvelteURLSearchParams('message=hello');

	let key = $state('key');
	let value = $state('value');
</script>

<input bind:value={key} />
<input bind:value={value} />
<button onclick={() => params.append(key, value)}>append</button>

<p>?{params.toString()}</p>

{#each params as [key, value]}
	<p>{key}: {value}</p>
{/each}
SvelteURLSearchParams
} from 'svelte/reactivity';

SvelteDate

A reactive version of the built-in Date object. Reading the date (whether with methods like date.getTime() or date.toString(), or via things like Intl.DateTimeFormat) in an effect or derived will cause it to be re-evaluated when the value of the date changes.

<script lang="ts">
	import { class SvelteDate

A reactive version of the built-in Date object. Reading the date (whether with methods like date.getTime() or date.toString(), or via things like Intl.DateTimeFormat) in an effect or derived will cause it to be re-evaluated when the value of the date changes.

<script>
	import { SvelteDate } from 'svelte/reactivity';

	const date = new SvelteDate();

	const formatter = new Intl.DateTimeFormat(undefined, {
	  hour: 'numeric',
	  minute: 'numeric',
	  second: 'numeric'
	});

	$effect(() => {
		const interval = setInterval(() => {
			date.setTime(Date.now());
		}, 1000);

		return () => {
			clearInterval(interval);
		};
	});
</script>

<p>The time is {formatter.format(date)}</p>
SvelteDate
} from 'svelte/reactivity';
const const date: SvelteDatedate = new new SvelteDate(...params: any[]): SvelteDate

A reactive version of the built-in Date object. Reading the date (whether with methods like date.getTime() or date.toString(), or via things like Intl.DateTimeFormat) in an effect or derived will cause it to be re-evaluated when the value of the date changes.

<script>
	import { SvelteDate } from 'svelte/reactivity';

	const date = new SvelteDate();

	const formatter = new Intl.DateTimeFormat(undefined, {
	  hour: 'numeric',
	  minute: 'numeric',
	  second: 'numeric'
	});

	$effect(() => {
		const interval = setInterval(() => {
			date.setTime(Date.now());
		}, 1000);

		return () => {
			clearInterval(interval);
		};
	});
</script>

<p>The time is {formatter.format(date)}</p>
SvelteDate
();
const const formatter: Intl.DateTimeFormatformatter = new Intl.
var Intl.DateTimeFormat: Intl.DateTimeFormatConstructor
new (locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions) => Intl.DateTimeFormat (+1 overload)
DateTimeFormat
(var undefinedundefined, {
Intl.DateTimeFormatOptions.hour?: "numeric" | "2-digit" | undefinedhour: 'numeric', Intl.DateTimeFormatOptions.minute?: "numeric" | "2-digit" | undefinedminute: 'numeric', Intl.DateTimeFormatOptions.second?: "numeric" | "2-digit" | undefinedsecond: 'numeric' });
function $effect(fn: () => void | (() => void)): void
namespace $effect

Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values. The timing of the execution is after the DOM has been updated.

Example:

$effect(() => console.log('The count is now ' + count));

If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.

Does not run during server-side rendering.

@see{@link https://svelte.dev/docs/svelte/$effect Documentation}@paramfn The function to execute
$
function $effect(fn: () => void | (() => void)): void
namespace $effect

Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values. The timing of the execution is after the DOM has been updated.

Example:

$effect(() => console.log('The count is now ' + count));

If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.

Does not run during server-side rendering.

@see{@link https://svelte.dev/docs/svelte/$effect Documentation}@paramfn The function to execute
effect
(() => {
const const interval: NodeJS.Timeoutinterval = function setInterval<[]>(callback: () => void, delay?: number): NodeJS.Timeout (+1 overload)setInterval(() => { const date: SvelteDatedate.Date.setTime(time: number): number

Sets the date and time value in the Date object.

@paramtime A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.
setTime
(var Date: DateConstructor

Enables basic storage and retrieval of dates and times.

Date
.DateConstructor.now(): number

Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).

now
());
}, 1000); return () => { function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void (+1 overload)clearInterval(const interval: NodeJS.Timeoutinterval); }; }); </script> <p>The time is {const formatter: Intl.DateTimeFormatformatter.Intl.DateTimeFormat.format(date?: Intl.FormattableTemporalObject | Date | number): string (+1 overload)format(const date: SvelteDatedate)}</p>
<script>
	import { class SvelteDate

A reactive version of the built-in Date object. Reading the date (whether with methods like date.getTime() or date.toString(), or via things like Intl.DateTimeFormat) in an effect or derived will cause it to be re-evaluated when the value of the date changes.

<script>
	import { SvelteDate } from 'svelte/reactivity';

	const date = new SvelteDate();

	const formatter = new Intl.DateTimeFormat(undefined, {
	  hour: 'numeric',
	  minute: 'numeric',
	  second: 'numeric'
	});

	$effect(() => {
		const interval = setInterval(() => {
			date.setTime(Date.now());
		}, 1000);

		return () => {
			clearInterval(interval);
		};
	});
</script>

<p>The time is {formatter.format(date)}</p>
SvelteDate
} from 'svelte/reactivity';
const const date: SvelteDatedate = new new SvelteDate(...params: any[]): SvelteDate

A reactive version of the built-in Date object. Reading the date (whether with methods like date.getTime() or date.toString(), or via things like Intl.DateTimeFormat) in an effect or derived will cause it to be re-evaluated when the value of the date changes.

<script>
	import { SvelteDate } from 'svelte/reactivity';

	const date = new SvelteDate();

	const formatter = new Intl.DateTimeFormat(undefined, {
	  hour: 'numeric',
	  minute: 'numeric',
	  second: 'numeric'
	});

	$effect(() => {
		const interval = setInterval(() => {
			date.setTime(Date.now());
		}, 1000);

		return () => {
			clearInterval(interval);
		};
	});
</script>

<p>The time is {formatter.format(date)}</p>
SvelteDate
();
const const formatter: Intl.DateTimeFormatformatter = new Intl.
var Intl.DateTimeFormat: Intl.DateTimeFormatConstructor
new (locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions) => Intl.DateTimeFormat (+1 overload)
DateTimeFormat
(var undefinedundefined, {
Intl.DateTimeFormatOptions.hour?: "numeric" | "2-digit" | undefinedhour: 'numeric', Intl.DateTimeFormatOptions.minute?: "numeric" | "2-digit" | undefinedminute: 'numeric', Intl.DateTimeFormatOptions.second?: "numeric" | "2-digit" | undefinedsecond: 'numeric' });
function $effect(fn: () => void | (() => void)): void
namespace $effect

Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values. The timing of the execution is after the DOM has been updated.

Example:

$effect(() => console.log('The count is now ' + count));

If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.

Does not run during server-side rendering.

@see{@link https://svelte.dev/docs/svelte/$effect Documentation}@paramfn The function to execute
$
function $effect(fn: () => void | (() => void)): void
namespace $effect

Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values. The timing of the execution is after the DOM has been updated.

Example:

$effect(() => console.log('The count is now ' + count));

If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.

Does not run during server-side rendering.

@see{@link https://svelte.dev/docs/svelte/$effect Documentation}@paramfn The function to execute
effect
(() => {
const const interval: NodeJS.Timeoutinterval = function setInterval<[]>(callback: () => void, delay?: number): NodeJS.Timeout (+1 overload)setInterval(() => { const date: SvelteDatedate.Date.setTime(time: number): number

Sets the date and time value in the Date object.

@paramtime A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.
setTime
(var Date: DateConstructor

Enables basic storage and retrieval of dates and times.

Date
.DateConstructor.now(): number

Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).

now
());
}, 1000); return () => { function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void (+1 overload)clearInterval(const interval: NodeJS.Timeoutinterval); }; }); </script> <p>The time is {const formatter: Intl.DateTimeFormatformatter.Intl.DateTimeFormat.format(date?: Intl.FormattableTemporalObject | Date | number): string (+1 overload)format(const date: SvelteDatedate)}</p>
export class class SvelteDateclass SvelteDateSvelteDate extends var Date: DateConstructor

Enables basic storage and retrieval of dates and times.

var Date: DateConstructor

Enables basic storage and retrieval of dates and times.

Date
{/*โ€ฆ*/}
constructor(...params: any[]);

SvelteSet

A reactive version of the built-in Set object. Reading contents of the set (by iterating, or by reading set.size or calling set.has(...) as in the example below) in an effect or derived will cause it to be re-evaluated as necessary when the set is updated.

Note that values in a reactive set are not made deeply reactive.

<script lang="ts">
	import { SvelteSet } from 'svelte/reactivity';
	let monkeys = new SvelteSet();

	function toggle(monkey) {
		if (monkeys.has(monkey)) {
			monkeys.delete(monkey);
		} else {
			monkeys.add(monkey);
		}
	}
</script>

{#each ['๐Ÿ™ˆ', '๐Ÿ™‰', '๐Ÿ™Š'] as monkey}
	<button onclick={() => toggle(monkey)}>{monkey}</button>
{/each}

<button onclick={() => monkeys.clear()}>clear</button>

{#if monkeys.has('๐Ÿ™ˆ')}<p>see no evil</p>{/if}
{#if monkeys.has('๐Ÿ™‰')}<p>hear no evil</p>{/if}
{#if monkeys.has('๐Ÿ™Š')}<p>speak no evil</p>{/if}
<script>
	import { SvelteSet } from 'svelte/reactivity';
	let monkeys = new SvelteSet();

	function toggle(monkey) {
		if (monkeys.has(monkey)) {
			monkeys.delete(monkey);
		} else {
			monkeys.add(monkey);
		}
	}
</script>

{#each ['๐Ÿ™ˆ', '๐Ÿ™‰', '๐Ÿ™Š'] as monkey}
	<button onclick={() => toggle(monkey)}>{monkey}</button>
{/each}

<button onclick={() => monkeys.clear()}>clear</button>

{#if monkeys.has('๐Ÿ™ˆ')}<p>see no evil</p>{/if}
{#if monkeys.has('๐Ÿ™‰')}<p>hear no evil</p>{/if}
{#if monkeys.has('๐Ÿ™Š')}<p>speak no evil</p>{/if}
export class class SvelteSet<T>class SvelteSet<T>SvelteSet<function (type parameter) T in SvelteSet<T>function (type parameter) T in SvelteSet<T>T> extends var Set: SetConstructorvar Set: SetConstructorSet<function (type parameter) T in SvelteSet<T>function (type parameter) T in SvelteSet<T>T> {/*โ€ฆ*/}
constructor(value?: Iterable<T> | null | undefined);
add(value: T): this;

SvelteMap

A reactive version of the built-in Map object. Reading contents of the map (by iterating, or by reading map.size or calling map.get(...) or map.has(...) as in the tic-tac-toe example below) in an effect or derived will cause it to be re-evaluated as necessary when the map is updated.

Note that values in a reactive map are not made deeply reactive.

<script lang="ts">
	import { SvelteMap } from 'svelte/reactivity';
	import { result } from './game.js';

	let board = new SvelteMap();
	let player = $state('x');
	let winner = $derived(result(board));

	function reset() {
		player = 'x';
		board.clear();
	}
</script>

<div class="board">
	{#each Array(9), i}
		<button
			disabled={board.has(i) || winner}
			onclick={() => {
				board.set(i, player);
				player = player === 'x' ? 'o' : 'x';
			}}
		>{board.get(i)}</button>
	{/each}
</div>

{#if winner}
	<p>{winner} wins!</p>
	<button onclick={reset}>reset</button>
{:else}
	<p>{player} is next</p>
{/if}
<script>
	import { SvelteMap } from 'svelte/reactivity';
	import { result } from './game.js';

	let board = new SvelteMap();
	let player = $state('x');
	let winner = $derived(result(board));

	function reset() {
		player = 'x';
		board.clear();
	}
</script>

<div class="board">
	{#each Array(9), i}
		<button
			disabled={board.has(i) || winner}
			onclick={() => {
				board.set(i, player);
				player = player === 'x' ? 'o' : 'x';
			}}
		>{board.get(i)}</button>
	{/each}
</div>

{#if winner}
	<p>{winner} wins!</p>
	<button onclick={reset}>reset</button>
{:else}
	<p>{player} is next</p>
{/if}
export class class SvelteMap<K, V>class SvelteMap<K, V>SvelteMap<function (type parameter) K in SvelteMap<K, V>function (type parameter) K in SvelteMap<K, V>K, function (type parameter) V in SvelteMap<K, V>function (type parameter) V in SvelteMap<K, V>V> extends var Map: MapConstructorvar Map: MapConstructorMap<function (type parameter) K in SvelteMap<K, V>function (type parameter) K in SvelteMap<K, V>K, function (type parameter) V in SvelteMap<K, V>function (type parameter) V in SvelteMap<K, V>V> {/*โ€ฆ*/}
constructor(value?: Iterable<readonly [K, V]> | null | undefined);
set(key: K, value: V): this;

SvelteURL

A reactive version of the built-in URL object. Reading properties of the URL (such as url.href or url.pathname) in an effect or derived will cause it to be re-evaluated as necessary when the URL changes.

The searchParams property is an instance of SvelteURLSearchParams.

Example:

<script lang="ts">
	import { class SvelteURL

A reactive version of the built-in URL object. Reading properties of the URL (such as url.href or url.pathname) in an effect or derived will cause it to be re-evaluated as necessary when the URL changes.

The searchParams property is an instance of SvelteURLSearchParams.

Example:

<script>
	import { SvelteURL } from 'svelte/reactivity';

	const url = new SvelteURL('https://example.com/path');
</script>

<!-- changes to these... -->
<input bind:value={url.protocol} />
<input bind:value={url.hostname} />
<input bind:value={url.pathname} />

<hr />

<!-- will update `href` and vice versa -->
<input bind:value={url.href} size="65" />
SvelteURL
} from 'svelte/reactivity';
const const url: SvelteURLurl = new new SvelteURL(url: string | URL, base?: string | URL): SvelteURL

A reactive version of the built-in URL object. Reading properties of the URL (such as url.href or url.pathname) in an effect or derived will cause it to be re-evaluated as necessary when the URL changes.

The searchParams property is an instance of SvelteURLSearchParams.

Example:

<script>
	import { SvelteURL } from 'svelte/reactivity';

	const url = new SvelteURL('https://example.com/path');
</script>

<!-- changes to these... -->
<input bind:value={url.protocol} />
<input bind:value={url.hostname} />
<input bind:value={url.pathname} />

<hr />

<!-- will update `href` and vice versa -->
<input bind:value={url.href} size="65" />
SvelteURL
('https://example.com/path');
</script> <!-- changes to these... --> <input bind:value={const url: SvelteURLurl.URL.protocol: string

The protocol property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".

MDN Reference

protocol
} />
<input bind:value={const url: SvelteURLurl.URL.hostname: string

The hostname property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN.

MDN Reference

hostname
} />
<input bind:value={const url: SvelteURLurl.URL.pathname: string

The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.

MDN Reference

pathname
} />
<hr /> <!-- will update `href` and vice versa --> <input bind:value={const url: SvelteURLurl.URL.href: string

The href property of the URL interface is a string containing the whole URL.

MDN Reference

href
} size="65" />
<script>
	import { class SvelteURL

A reactive version of the built-in URL object. Reading properties of the URL (such as url.href or url.pathname) in an effect or derived will cause it to be re-evaluated as necessary when the URL changes.

The searchParams property is an instance of SvelteURLSearchParams.

Example:

<script>
	import { SvelteURL } from 'svelte/reactivity';

	const url = new SvelteURL('https://example.com/path');
</script>

<!-- changes to these... -->
<input bind:value={url.protocol} />
<input bind:value={url.hostname} />
<input bind:value={url.pathname} />

<hr />

<!-- will update `href` and vice versa -->
<input bind:value={url.href} size="65" />
SvelteURL
} from 'svelte/reactivity';
const const url: SvelteURLurl = new new SvelteURL(url: string | URL, base?: string | URL): SvelteURL

A reactive version of the built-in URL object. Reading properties of the URL (such as url.href or url.pathname) in an effect or derived will cause it to be re-evaluated as necessary when the URL changes.

The searchParams property is an instance of SvelteURLSearchParams.

Example:

<script>
	import { SvelteURL } from 'svelte/reactivity';

	const url = new SvelteURL('https://example.com/path');
</script>

<!-- changes to these... -->
<input bind:value={url.protocol} />
<input bind:value={url.hostname} />
<input bind:value={url.pathname} />

<hr />

<!-- will update `href` and vice versa -->
<input bind:value={url.href} size="65" />
SvelteURL
('https://example.com/path');
</script> <!-- changes to these... --> <input bind:value={const url: SvelteURLurl.URL.protocol: string

The protocol property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".

MDN Reference

protocol
} />
<input bind:value={const url: SvelteURLurl.URL.hostname: string

The hostname property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN.

MDN Reference

hostname
} />
<input bind:value={const url: SvelteURLurl.URL.pathname: string

The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.

MDN Reference

pathname
} />
<hr /> <!-- will update `href` and vice versa --> <input bind:value={const url: SvelteURLurl.URL.href: string

The href property of the URL interface is a string containing the whole URL.

MDN Reference

href
} size="65" />
export class class SvelteURLclass SvelteURLSvelteURL extends 
var URL: {
    new (url: string | URL, base?: string | URL): URL;
    prototype: URL;
    canParse(url: string | URL, base?: string | URL): boolean;
    createObjectURL(obj: Blob | MediaSource): string;
    parse(url: string | URL, base?: string | URL): URL | null;
    revokeObjectURL(url: string): void;
}

The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.

MDN Reference

var URL: {
    new (url: string | URL, base?: string | URL): URL;
    prototype: URL;
    canParse(url: string | URL, base?: string | URL): boolean;
    createObjectURL(obj: Blob | MediaSource): string;
    parse(url: string | URL, base?: string | URL): URL | null;
    revokeObjectURL(url: string): void;
}

The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.

MDN Reference

URL
{/*โ€ฆ*/}
get searchParams(): SvelteURLSearchParams;

SvelteURLSearchParams

A reactive version of the built-in URLSearchParams object. Reading its contents (by iterating, or by calling params.get(...) or params.getAll(...) as in the example below) in an effect or derived will cause it to be re-evaluated as necessary when the params are updated.

<script lang="ts">
	import { class SvelteURLSearchParams

A reactive version of the built-in URLSearchParams object. Reading its contents (by iterating, or by calling params.get(...) or params.getAll(...) as in the example below) in an effect or derived will cause it to be re-evaluated as necessary when the params are updated.

<script>
	import { SvelteURLSearchParams } from 'svelte/reactivity';

	const params = new SvelteURLSearchParams('message=hello');

	let key = $state('key');
	let value = $state('value');
</script>

<input bind:value={key} />
<input bind:value={value} />
<button onclick={() => params.append(key, value)}>append</button>

<p>?{params.toString()}</p>

{#each params as [key, value]}
	<p>{key}: {value}</p>
{/each}
SvelteURLSearchParams
} from 'svelte/reactivity';
const const params: SvelteURLSearchParamsparams = new new SvelteURLSearchParams(init?: string[][] | Record<string, string> | string | URLSearchParams): SvelteURLSearchParams

A reactive version of the built-in URLSearchParams object. Reading its contents (by iterating, or by calling params.get(...) or params.getAll(...) as in the example below) in an effect or derived will cause it to be re-evaluated as necessary when the params are updated.

<script>
	import { SvelteURLSearchParams } from 'svelte/reactivity';

	const params = new SvelteURLSearchParams('message=hello');

	let key = $state('key');
	let value = $state('value');
</script>

<input bind:value={key} />
<input bind:value={value} />
<button onclick={() => params.append(key, value)}>append</button>

<p>?{params.toString()}</p>

{#each params as [key, value]}
	<p>{key}: {value}</p>
{/each}
SvelteURLSearchParams
('message=hello');
let let key: stringkey =
function $state<"key">(initial: "key"): "key" (+1 overload)
namespace $state

Declares reactive state.

Example:

let count = $state(0);
@see{@link https://svelte.dev/docs/svelte/$state Documentation}@paraminitial The initial value
$
function $state<"key">(initial: "key"): "key" (+1 overload)
namespace $state

Declares reactive state.

Example:

let count = $state(0);
@see{@link https://svelte.dev/docs/svelte/$state Documentation}@paraminitial The initial value
state
('key');
let let value: stringvalue =
function $state<"value">(initial: "value"): "value" (+1 overload)
namespace $state

Declares reactive state.

Example:

let count = $state(0);
@see{@link https://svelte.dev/docs/svelte/$state Documentation}@paraminitial The initial value
$
function $state<"value">(initial: "value"): "value" (+1 overload)
namespace $state

Declares reactive state.

Example:

let count = $state(0);
@see{@link https://svelte.dev/docs/svelte/$state Documentation}@paraminitial The initial value
state
('value');
</script> <input bind:value={let key: stringkey} /> <input bind:value={let value: stringvalue} /> <button onclick={() => const params: SvelteURLSearchParamsparams.URLSearchParams.append(name: string, value: string): void

The append() method of the URLSearchParams interface appends a specified key/value pair as a new search parameter.

MDN Reference

append
(let key: stringkey, let value: stringvalue)}>append</button>
<p>?{const params: SvelteURLSearchParamsparams.URLSearchParams.toString(): stringtoString()}</p> {#each const params: SvelteURLSearchParamsparams as [let key: stringkey, let value: stringvalue]} <p>{let key: stringkey}: {let value: stringvalue}</p> {/each}
<script>
	import { class SvelteURLSearchParams

A reactive version of the built-in URLSearchParams object. Reading its contents (by iterating, or by calling params.get(...) or params.getAll(...) as in the example below) in an effect or derived will cause it to be re-evaluated as necessary when the params are updated.

<script>
	import { SvelteURLSearchParams } from 'svelte/reactivity';

	const params = new SvelteURLSearchParams('message=hello');

	let key = $state('key');
	let value = $state('value');
</script>

<input bind:value={key} />
<input bind:value={value} />
<button onclick={() => params.append(key, value)}>append</button>

<p>?{params.toString()}</p>

{#each params as [key, value]}
	<p>{key}: {value}</p>
{/each}
SvelteURLSearchParams
} from 'svelte/reactivity';
const const params: SvelteURLSearchParamsparams = new new SvelteURLSearchParams(init?: string[][] | Record<string, string> | string | URLSearchParams): SvelteURLSearchParams

A reactive version of the built-in URLSearchParams object. Reading its contents (by iterating, or by calling params.get(...) or params.getAll(...) as in the example below) in an effect or derived will cause it to be re-evaluated as necessary when the params are updated.

<script>
	import { SvelteURLSearchParams } from 'svelte/reactivity';

	const params = new SvelteURLSearchParams('message=hello');

	let key = $state('key');
	let value = $state('value');
</script>

<input bind:value={key} />
<input bind:value={value} />
<button onclick={() => params.append(key, value)}>append</button>

<p>?{params.toString()}</p>

{#each params as [key, value]}
	<p>{key}: {value}</p>
{/each}
SvelteURLSearchParams
('message=hello');
let let key: stringkey =
function $state<"key">(initial: "key"): "key" (+1 overload)
namespace $state

Declares reactive state.

Example:

let count = $state(0);
@see{@link https://svelte.dev/docs/svelte/$state Documentation}@paraminitial The initial value
$
function $state<"key">(initial: "key"): "key" (+1 overload)
namespace $state

Declares reactive state.

Example:

let count = $state(0);
@see{@link https://svelte.dev/docs/svelte/$state Documentation}@paraminitial The initial value
state
('key');
let let value: stringvalue =
function $state<"value">(initial: "value"): "value" (+1 overload)
namespace $state

Declares reactive state.

Example:

let count = $state(0);
@see{@link https://svelte.dev/docs/svelte/$state Documentation}@paraminitial The initial value
$
function $state<"value">(initial: "value"): "value" (+1 overload)
namespace $state

Declares reactive state.

Example:

let count = $state(0);
@see{@link https://svelte.dev/docs/svelte/$state Documentation}@paraminitial The initial value
state
('value');
</script> <input bind:value={let key: stringkey} /> <input bind:value={let value: stringvalue} /> <button onclick={() => const params: SvelteURLSearchParamsparams.URLSearchParams.append(name: string, value: string): void

The append() method of the URLSearchParams interface appends a specified key/value pair as a new search parameter.

MDN Reference

append
(let key: stringkey, let value: stringvalue)}>append</button>
<p>?{const params: SvelteURLSearchParamsparams.URLSearchParams.toString(): stringtoString()}</p> {#each const params: SvelteURLSearchParamsparams as [let key: stringkey, let value: stringvalue]} <p>{let key: stringkey}: {let value: stringvalue}</p> {/each}
export class class SvelteURLSearchParamsclass SvelteURLSearchParamsSvelteURLSearchParams extends 
var URLSearchParams: {
    new (init?: string[][] | Record<string, string> | string | URLSearchParams): URLSearchParams;
    prototype: URLSearchParams;
}

The URLSearchParams interface defines utility methods to work with the query string of a URL.

MDN Reference

var URLSearchParams: {
    new (init?: string[][] | Record<string, string> | string | URLSearchParams): URLSearchParams;
    prototype: URLSearchParams;
}

The URLSearchParams interface defines utility methods to work with the query string of a URL.

MDN Reference

URLSearchParams
{/*โ€ฆ*/}
[REPLACE](params: URLSearchParams): void;

MediaQuery

Available since 5.7.0

Creates a media query and provides a current property that reflects whether or not it matches.

Use it carefully โ€” during server-side rendering, there is no way to know what the correct value should be, potentially causing content to change upon hydration. If you can use the media query in CSS to achieve the same effect, do that.

<script lang="ts">
	import { class MediaQuery

Creates a media query and provides a current property that reflects whether or not it matches.

Use it carefully โ€” during server-side rendering, there is no way to know what the correct value should be, potentially causing content to change upon hydration. If you can use the media query in CSS to achieve the same effect, do that.

<script>
	import { MediaQuery } from 'svelte/reactivity';

	const large = new MediaQuery('min-width: 800px');
</script>

<h1>{large.current ? 'large screen' : 'small screen'}</h1>
@extendsReactiveValue<boolean> *@since5.7.0
MediaQuery
} from 'svelte/reactivity';
const const large: MediaQuerylarge = new new MediaQuery(query: string, fallback?: boolean | undefined): MediaQuery
@paramquery A media query string@paramfallback Fallback value for the server
MediaQuery
('min-width: 800px');
</script> <h1>{const large: MediaQuerylarge.ReactiveValue<boolean>.current: booleancurrent ? 'large screen' : 'small screen'}</h1>
<script>
	import { class MediaQuery

Creates a media query and provides a current property that reflects whether or not it matches.

Use it carefully โ€” during server-side rendering, there is no way to know what the correct value should be, potentially causing content to change upon hydration. If you can use the media query in CSS to achieve the same effect, do that.

<script>
	import { MediaQuery } from 'svelte/reactivity';

	const large = new MediaQuery('min-width: 800px');
</script>

<h1>{large.current ? 'large screen' : 'small screen'}</h1>
@extendsReactiveValue<boolean> *@since5.7.0
MediaQuery
} from 'svelte/reactivity';
const const large: MediaQuerylarge = new new MediaQuery(query: string, fallback?: boolean | undefined): MediaQuery
@paramquery A media query string@paramfallback Fallback value for the server
MediaQuery
('min-width: 800px');
</script> <h1>{const large: MediaQuerylarge.ReactiveValue<boolean>.current: booleancurrent ? 'large screen' : 'small screen'}</h1>
export class MediaQuery extends ReactiveValue<boolean> {/*โ€ฆ*/}
constructor(query: string, fallback?: boolean | undefined);

createSubscriber

Available since 5.7.0

Returns a subscribe function that integrates external event-based systems with Svelte's reactivity. It's particularly useful for integrating with web APIs like MediaQuery, IntersectionObserver, or WebSocket.

If subscribe is called inside an effect (including indirectly, for example inside a getter), the start callback will be called with an update function. Whenever update is called, the effect re-runs.

If start returns a cleanup function, it will be called when the effect is destroyed.

If subscribe is called in multiple effects, start will only be called once as long as the effects are active, and the returned teardown function will only be called when all effects are destroyed.

It's best understood with an example. Here's an implementation of MediaQuery:

import { createSubscriber } from 'svelte/reactivity';
import { on } from 'svelte/events';

export class MediaQuery {
	#query;
	#subscribe;

	constructor(query) {
		this.#query = window.matchMedia(`(${query})`);

		this.#subscribe = createSubscriber((update) => {
			// when the `change` event occurs, re-run any effects that read `this.current`
			const off = on(this.#query, 'change', update);

			// stop listening when all the effects are destroyed
			return () => off();
		});
	}

	get current() {
		// This makes the getter reactive, if read in an effect
		this.#subscribe();

		// Return the current state of the query, whether or not we're in an effect
		return this.#query.matches;
	}
}
export function createSubscriber(start: (update: () => void) => (() => void) | void): () => void;