Reactive Built-ins: `Date`, `URL`, and `URLSearchParams` in Svelte

Introduction to Reactive Built-ins

Using `SvelteDate` for Reactive Dates

SvelteDate is a reactive version of JavaScript’s built-in Date object. It allows you to work with dates in a way that automatically updates the UI whenever the date changes. Unlike regular Date objects, SvelteDate is mutable, meaning you can update its value directly without needing to reassign it.

Here’s an example of how to use SvelteDate to display the current time:

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

    let currentDate = new SvelteDate();

    $effect(() => {
        const interval = setInterval(() => {
            currentDate.setTime(Date.now()); // Update the existing instance
        }, 1000);

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

<h3>Current Time</h3>
<p>{currentDate.toLocaleTimeString()}</p>

In this example, we create a SvelteDate instance called currentDate. The $effect rune sets up an interval that updates currentDate every second. Because SvelteDate is reactive, the UI automatically reflects the updated time without requiring additional logic. The cleanup function ensures the interval is cleared when the component is destroyed, preventing memory leaks.

When you run this code, you’ll see the current time displayed, updating every second.

Using `SvelteURL` and `URLSearchParams` for Reactive URLs

SvelteURL is a reactive version of JavaScript’s URL object. It allows you to work with URLs in a way that automatically updates the UI whenever the URL changes. Like SvelteDate, SvelteURL is mutable, so you can update its properties directly.

Here’s an example of how to use SvelteURL to manage and update query parameters:

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

    let url = new SvelteURL('https://example.com?foo=1&bar=2');

    function updateQueryParam() {
        url.searchParams.set('foo', String(Number(url.searchParams.get('foo')) + 1));
    }
</script>

<h3>Reactive URL</h3>
<p><strong>Current URL:</strong> {url.href}</p>
<button onclick={updateQueryParam}>Increment 'foo' Query Param</button>

In this example, we create a SvelteURL instance called url with an initial query string. The updateQueryParam function increments the value of the foo query parameter by 1. Because SvelteURL is reactive, the UI automatically updates to reflect the new URL whenever the query parameter changes.

When you run this code, you’ll see the current URL displayed, and clicking the button will increment the foo query parameter.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal