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 cc5dc20
Showing 1 changed file with 93 additions and 0 deletions.
93 changes: 93 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,97 @@ 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. Alternatively, the whole object can be rewritten on update, which may actually lead to better performance than deep reactive `$state`.

```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 -->
<button
onclick={() => {
people.set("carol", {name: "Carol", age: 0});
}}
>
Carol was born
</button>
{#if people.has("carol")}
<!-- This WILL propagate reactively -->
<button
onclick={() => {
const oldValue = people.get("carol");
people.set("carol", {...oldValue, age: oldValue.age + 1});
}}
>
Carol's birthday
</button>
{/if}
```

> MODULE: svelte/reactivity

0 comments on commit cc5dc20

Please sign in to comment.