8000 tweak docs · sveltejs/svelte@bde0252 · GitHub
[go: up one dir, main page]

Skip to content

Commit bde0252

Browse files
committed
tweak docs
1 parent bfa0883 commit bde0252

File tree

1 file changed

+5
-18
lines changed

1 file changed

+5
-18
lines changed

documentation/docs/02-runes/02-$state.md

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -149,32 +149,19 @@ This can improve performance with large arrays and objects that you weren't plan
149149

150150
## State options
151151

152-
Both `$state` and `$state.raw` can optionally accept a second argument. This allows you to specify an `onchange` function that will be called synchronously whenever the state value changes (for `$state` it will also be called for deep mutations).
152+
Both `$state` and `$state.raw` accept an optional second argument that includes an `onchange` function.
153153

154-
The `onchange` function is untracked so even if you assign within an `$effect` it will not cause unwanted dependencies.
154+
This function is called synchronously whenever the value is reassigned or (for `$state`) mutated, allowing you to respond to changes before [effects]($effect) run. It's useful for — for example — persisting data, or validating it:
155155

156156
```js
157157
let count = $state(0, {
158-
onchange(){
159-
console.log("count is now", count);
158+
onchange() {
159+
count = Math.min(count, 10);
160160
}
161161
});
162-
163-
// this will log "count is now 1"
164-
count++;
165162
```
166163

167-
this could be especially useful if you want to sync some stateful variable that could be mutated without using an effect.
168-
169-
```js
170-
let array = $state([], {
171-
onchange(){
172-
localStorage.setItem('array', JSON.stringify(array));
173-
}
174-
});
175-
176-
array.push(array.length);
177-
```
164+
> The `onchange` function is [untracked](svelte#untrack).
178165
179166
## `$state.snapshot`
180167

0 commit comments

Comments
 (0)
0