|
1 | 1 | # $state Definition |
2 | 2 |
|
3 | | -**Definition:** Creates reactive state that triggers UI updates when |
4 | | -the value changes |
5 | | -**Syntax:** `$state<T>(initial: T): T` | |
6 | | -`$state<T>(): T | undefined` |
7 | | -**Parameters:** |
8 | | - |
9 | | -- `initial` - The initial value (optional) |
10 | | - **Returns:** Reactive proxy of the initial value |
11 | | - **Variants:** |
12 | | -- `$state.raw<T>(initial: T): T` - Non-deeply-reactive state |
13 | | -- `$state.snapshot<T>(state: T): Snapshot<T>` - Static snapshot of |
14 | | - reactive state |
| 3 | +**Definition:** Declares reactive state. When the value changes, the |
| 4 | +UI updates. Arrays and plain objects become deeply reactive proxies; |
| 5 | +primitives (like numbers/strings/booleans) remain normal values. |
| 6 | +**Also see:** `$state.raw`, `$state.snapshot` |
15 | 7 |
|
16 | 8 | ## Examples |
17 | 9 |
|
18 | | -```js |
| 10 | +```ts |
19 | 11 | // Basic reactive state |
20 | 12 | let count = $state(0); |
21 | | -count++; // Triggers reactivity |
| 13 | +count++; // triggers an update |
22 | 14 |
|
23 | | -// Object state (deeply reactive) |
| 15 | +// Object/array state (deeply reactive) |
24 | 16 | let user = $state({ name: 'Alice', age: 30 }); |
25 | | -user.name = 'Bob'; // Triggers reactivity |
| 17 | +user.name = 'Bob'; // triggers an update of only the places that read `user.name` |
26 | 18 |
|
27 | | -// Optional initial value |
| 19 | +// You can declare without an initial value with generics |
28 | 20 | let data = $state<string>(); // undefined initially |
29 | 21 | ``` |
30 | 22 |
|
31 | 23 | ## Notes |
32 | 24 |
|
33 | | -- Deep reactivity: Arrays and simple objects are proxied deeply, so |
34 | | - property changes and array methods (e.g., `push`) trigger granular |
| 25 | +- Deep reactivity: Arrays and simple objects are proxied deeply; |
| 26 | + property changes and array methods (e.g. `push`) trigger granular |
35 | 27 | updates. |
36 | 28 | - Raw state: Use `$state.raw` to avoid deep reactivity and update only |
37 | 29 | on reassignment for performance with large data. |
|
0 commit comments