Skip to content

Commit

Permalink
Expanded svelte/reactivity documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
marekdedic committed Dec 21, 2024
1 parent 999b92d commit bdc61c7
Showing 1 changed file with 81 additions and 0 deletions.
81 changes: 81 additions & 0 deletions documentation/docs/98-reference/21-svelte-reactivity.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,85 @@ Svelte provides reactive versions of various built-ins like `SvelteMap`, `Svelte
<input bind:value={url.href} />
```

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.

```svelte
<script>
import { SvelteURL } from 'svelte/reactivity';
let url = $state(new SvelteURL('https://example.com/path'));
</script>
<!-- these are reactive... -->
Protocol: {url?.protocol ?? "ftp:"}
<br>
Hostname: {url?.hostname ?? "svelte.dev"}
<br>
Path: {url?.pathname ?? ""}
<hr />
<!-- ...even when reassigning -->
<button
onclick={() => {
url = undefined;
}}
>
Erase
</button>
```

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.

```svelte
<script>
import { SvelteMap } from 'svelte/reactivity';
const people = new SvelteMap();
const alice = {name: "Alice", age: 18};
people.set("alice", alice);
const bob = $state({name: "Bob", age: 21});
people.set("bob", bob);
</script>
{#each people.entries() as [id, person] (id)}
Name: {person.name}
<br>
Age: {person.age}
<br>
<br>
{/each}
<hr />
<!-- This will NOT propagate reactively -->
<button
onclick={() => {
people.get("alice").age++;
}}
>
Alice's birthday
</button>
<!-- This WILL propagate reactively -->
<button
onclick={() => {
people.get("bob").age++;
}}
>
Bob's birthday
</button>
<!-- This WILL propagate reactively (but subsequent updates to the object won't) -->
<button
onclick={() => {
people.set("carol", {name: "Carol", age: 0});
}}
>
Carol was born
</button>
```

> MODULE: svelte/reactivity

0 comments on commit bdc61c7

Please sign in to comment.