Skip to content

Commit 2e2f4fe

Browse files
committed
docs
1 parent d41d252 commit 2e2f4fe

File tree

1 file changed

+19
-12
lines changed
  • sites/svelte-5-preview/src/routes/docs/content/01-api

1 file changed

+19
-12
lines changed

sites/svelte-5-preview/src/routes/docs/content/01-api/02-runes.md

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -66,25 +66,32 @@ In non-runes mode, a `let` declaration is treated as reactive state if it is upd
6666

6767
## `$state.frozen`
6868

69-
Similar to `$state`, `$state.frozen` is also declared and can be used in many of the same ways (including on classes). However, the properties of any object and arrays are treated as read-only, and cannot be mutated. So if you intend to use objects as state and you want to mutate their properties and have reactivity work by default, it's recommended you use `$state` instead.
69+
State declared with `$state.frozen` cannot be mutated; it can only be _reassigned_. In other words, rather than assigning to a property of an object, or using an array method like `push`, replace the object or array altogether:
7070

71-
For the cases where you don't want Svelte's reactivity to apply deeply to state, and for those who might want to have more control over their data structures, you might find `$state.frozen` useful. Furthermore, `$state.frozen` is ideal for those who want to work with data using immutable patterns rather than mutable patterns.
72-
73-
```svelte
71+
```diff
7472
<script>
75-
let items = $state.frozen([0]);
76-
77-
const addItem = () => {
78-
items = [...items, items.length];
79-
};
73+
- let numbers = $state([1, 2, 3]);
74+
+ let numbers = $state.frozen([1, 2, 3]);
8075
</script>
8176

82-
<button on:click={addItem}>
83-
{items.join(', ')}
77+
-<button onclick={() => numbers.push(numbers.length + 1)}>
78+
+<button onclick={() => numbers = [...numbers, numbers.length + 1]}>
79+
push
8480
</button>
81+
82+
-<button onclick={() => numbers.pop()}> pop </button>
83+
+<button onclick={() => numbers = numbers.slice(0, -1)}> pop </button>
84+
85+
<p>
86+
{numbers.join(' + ') || 0}
87+
=
88+
{numbers.reduce((a, b) => a + b, 0)}
89+
</p>
8590
```
8691

87-
> Objects and arrays passed to `$state.frozen` will be shallowly frozen using `Object.freeze()`. If you don't want them to be frozen, then you should pass in a clone of the object or array you want to use.
92+
This can improve performance with large arrays and objects that you weren't planning to mutate anyway, since it avoids the cost of making them reactive. Note that frozen state can _contain_ reactive state (for example, a frozen array of reactive objects).
93+
94+
> Objects and arrays passed to `$state.frozen` will be shallowly frozen using `Object.freeze()`. If you don't want this, pass in a clone of the object or array instead.
8895
8996
## `$derived`
9097

0 commit comments

Comments
 (0)