You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: documentation/docs/98-reference/21-svelte-reactivity.md
+93
Original file line number
Diff line number
Diff line change
@@ -22,4 +22,97 @@ Svelte provides reactive versions of various built-ins like `SvelteMap`, `Svelte
22
22
<input bind:value={url.href} />
23
23
```
24
24
25
+
The utilities provided in `svelte/reactivity` are automatically reactive with respect to their properties and methods, as seen in the previous example. As such, they don't need to be wrapped in `$state`. However, if a variable is reassigned, it needs to be wrapped in a `$state` in order for this reassignement to be reactive.
26
+
27
+
```svelte
28
+
<script>
29
+
import { SvelteURL } from 'svelte/reactivity';
30
+
31
+
let url = $state(new SvelteURL('https://example.com/path'));
32
+
</script>
33
+
34
+
<!-- these are reactive... -->
35
+
Protocol: {url?.protocol ?? "ftp:"}
36
+
<br>
37
+
Hostname: {url?.hostname ?? "svelte.dev"}
38
+
<br>
39
+
Path: {url?.pathname ?? ""}
40
+
41
+
<hr />
42
+
43
+
<!-- ...even when reassigning -->
44
+
<button
45
+
onclick={() => {
46
+
url = undefined;
47
+
}}
48
+
>
49
+
Erase
50
+
</button>
51
+
```
52
+
53
+
In a similar manner, the values stored inside e.g. `SvelteMap` are not automatically reactive, so if more complex values such as objects are used, they need to be wrapped in a `$state` in order to make their properties reactive as well. Alternatively, the whole object can be rewritten on update, which may actually lead to better performance than deep reactive `$state`.
0 commit comments