Svelte โข Reference
svelte/reactivity
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): () => voidReturns 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;
}
}
function createSubscriber(start: (update: () => void) => (() => void) | void): () => voidReturns 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;
}
}
createSubscriber,
class MediaQueryCreates 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>
class MediaQueryCreates 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>
MediaQuery,
class SvelteDateA 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 SvelteDateA 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 SvelteURLA 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.
<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 SvelteURLA 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.
<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 SvelteURLSearchParamsA 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 SvelteURLSearchParamsA 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 SvelteDateA 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[]): SvelteDateA 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.
$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.
effect(() => {
const const interval: NodeJS.Timeoutinterval = function setInterval<[]>(callback: () => void, delay?: number): NodeJS.Timeout (+1 overload)setInterval(() => {
const date: SvelteDatedate.Date.setTime(time: number): numberSets the date and time value in the Date object.
setTime(var Date: DateConstructorEnables basic storage and retrieval of dates and times.
Date.DateConstructor.now(): numberReturns 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 SvelteDateA 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[]): SvelteDateA 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.
$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.
effect(() => {
const const interval: NodeJS.Timeoutinterval = function setInterval<[]>(callback: () => void, delay?: number): NodeJS.Timeout (+1 overload)setInterval(() => {
const date: SvelteDatedate.Date.setTime(time: number): numberSets the date and time value in the Date object.
setTime(var Date: DateConstructorEnables basic storage and retrieval of dates and times.
Date.DateConstructor.now(): numberReturns 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: DateConstructorEnables basic storage and retrieval of dates and times.
var Date: DateConstructorEnables 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.
<script lang="ts">
import { class SvelteURLA 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.
<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): SvelteURLA 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.
<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: stringThe protocol property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".
protocol} />
<input bind:value={const url: SvelteURLurl.URL.hostname: stringThe 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.
hostname} />
<input bind:value={const url: SvelteURLurl.URL.pathname: stringThe 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.
pathname} />
<hr />
<!-- will update `href` and vice versa -->
<input bind:value={const url: SvelteURLurl.URL.href: stringThe href property of the URL interface is a string containing the whole URL.
href} size="65" /><script>
import { class SvelteURLA 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.
<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): SvelteURLA 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.
<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: stringThe protocol property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".
protocol} />
<input bind:value={const url: SvelteURLurl.URL.hostname: stringThe 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.
hostname} />
<input bind:value={const url: SvelteURLurl.URL.pathname: stringThe 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.
pathname} />
<hr />
<!-- will update `href` and vice versa -->
<input bind:value={const url: SvelteURLurl.URL.href: stringThe href property of the URL interface is a string containing the whole URL.
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.
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.
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 SvelteURLSearchParamsA 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): SvelteURLSearchParamsA 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);
$function $state<"key">(initial: "key"): "key" (+1 overload)
namespace $state
Declares reactive state.
Example:
let count = $state(0);
state('key');
let let value: stringvalue = function $state<"value">(initial: "value"): "value" (+1 overload)
namespace $state
Declares reactive state.
Example:
let count = $state(0);
$function $state<"value">(initial: "value"): "value" (+1 overload)
namespace $state
Declares reactive state.
Example:
let count = $state(0);
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): voidThe append() method of the URLSearchParams interface appends a specified key/value pair as a new search parameter.
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 SvelteURLSearchParamsA 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): SvelteURLSearchParamsA 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);
$function $state<"key">(initial: "key"): "key" (+1 overload)
namespace $state
Declares reactive state.
Example:
let count = $state(0);
state('key');
let let value: stringvalue = function $state<"value">(initial: "value"): "value" (+1 overload)
namespace $state
Declares reactive state.
Example:
let count = $state(0);
$function $state<"value">(initial: "value"): "value" (+1 overload)
namespace $state
Declares reactive state.
Example:
let count = $state(0);
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): voidThe append() method of the URLSearchParams interface appends a specified key/value pair as a new search parameter.
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.
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.
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 MediaQueryCreates 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>
MediaQuery } from 'svelte/reactivity';
const const large: MediaQuerylarge = new new MediaQuery(query: string, fallback?: boolean | undefined): MediaQueryMediaQuery('min-width: 800px');
</script>
<h1>{const large: MediaQuerylarge.ReactiveValue<boolean>.current: booleancurrent ? 'large screen' : 'small screen'}</h1><script>
import { class MediaQueryCreates 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>
MediaQuery } from 'svelte/reactivity';
const const large: MediaQuerylarge = new new MediaQuery(query: string, fallback?: boolean | undefined): MediaQueryMediaQuery('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;