Reactive Built-ins: `Date`, `URL`, and `URLSearchParams` in Svelte
Introduction to Reactive Built-ins
In the previous lesson, you learned how to use the $effect rune in Svelte to manage reactive side effects, such as timers and DOM updates. Now, we’ll explore another powerful feature of Svelte: reactive built-ins. These are special objects like SvelteDate and SvelteURL that are designed to work seamlessly with Svelte’s reactivity system. Unlike regular variables, these built-ins don’t require $stateto be reactive. Instead, they are inherently reactive, making them ideal for handling dynamic data like dates and URLs.
In this lesson, you’ll learn how to use SvelteDate to create a reactive clock and SvelteURL to manage and update query parameters dynamically. By the end, you’ll be able to build applications that respond to changes in dates and URLs without writing complex reactivity logic. Let’s dive in!
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:
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:
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.
