Skip to content

Commit 5a8fa69

Browse files
authored
feat: make deriveds writable (#15570)
* feat: make deriveds writable * add optimistic UI example * add note to when-not-to-use-effect * add section on deep reactivity * root-relative URL * use hash URL * mention const * make handler async, move into script block
1 parent 2d3b65d commit 5a8fa69

File tree

22 files changed

+105
-175
lines changed

22 files changed

+105
-175
lines changed

.changeset/clever-terms-tell.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': minor
3+
---
4+
5+
feat: make deriveds writable

documentation/docs/02-runes/03-$derived.md

+42
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,48 @@ Anything read synchronously inside the `$derived` expression (or `$derived.by` f
5252

5353
To exempt a piece of state from being treated as a dependency, use [`untrack`](svelte#untrack).
5454

55+
## Overriding derived values
56+
57+
Derived expressions are recalculated when their dependencies change, but you can temporarily override their values by reassigning them (unless they are declared with `const`). This can be useful for things like _optimistic UI_, where a value is derived from the 'source of truth' (such as data from your server) but you'd like to show immediate feedback to the user:
58+
59+
```svelte
60+
<script>
61+
let { post, like } = $props();
62+
63+
let likes = $derived(post.likes);
64+
65+
async function onclick() {
66+
// increment the `likes` count immediately...
67+
likes += 1;
68+
69+
// and tell the server, which will eventually update `post`
70+
try {
71+
await like();
72+
} catch {
73+
// failed! roll back the change
74+
likes -= 1;
75+
}
76+
}
77+
</script>
78+
79+
<button {onclick}>🧡 {likes}</button>
80+
```
81+
82+
> [!NOTE] Prior to Svelte 5.25, deriveds were read-only.
83+
84+
## Deriveds and reactivity
85+
86+
Unlike `$state`, which converts objects and arrays to [deeply reactive proxies]($state#Deep-state), `$derived` values are left as-is. For example, [in a case like this](/playground/untitled#H4sIAAAAAAAAE4VU22rjMBD9lUHd3aaQi9PdstS1A3t5XvpQ2Ic4D7I1iUUV2UjjNMX431eS7TRdSosxgjMzZ45mjt0yzffIYibvy0ojFJWqDKCQVBk2ZVup0LJ43TJ6rn2aBxw-FP2o67k9oCKP5dziW3hRaUJNjoYltjCyplWmM1JIIAn3FlL4ZIkTTtYez6jtj4w8WwyXv9GiIXiQxLVs9pfTMR7EuoSLIuLFbX7Z4930bZo_nBrD1bs834tlfvsBz9_SyX6PZXu9XaL4gOWn4sXjeyzftv4ZWfyxubpzxzg6LfD4MrooxELEosKCUPigQCMPKCZh0OtQE1iSxcsmdHuBvCiHZXALLXiN08EL3RRkaJ_kDVGle0HcSD5TPEeVtj67O4Nrg9aiSNtBY5oODJkrL5QsHtN2cgXp6nSJMWzpWWGasdlsGEMbzi5jPr5KFr0Ep7pdeM2-TCelCddIhDxAobi1jqF3cMaC1RKp64bAW9iFAmXGIHfd4wNXDabtOLN53w8W53VvJoZLh7xk4Rr3CoL-UNoLhWHrT1JQGcM17u96oES5K-kc2XOzkzqGCKL5De79OUTyyrg1zgwXsrEx3ESfx4Bz0M5UjVMHB24mw9SuXtXFoN13fYKOM1tyUT3FbvbWmSWCZX2Er-41u5xPoml45svRahl9Wb9aasbINJixDZwcPTbyTLZSUsAvrg_cPuCR7s782_WU8343Y72Qtlb8OYatwuOQvuN13M_hJKNfxann1v1U_B1KZ_D_mzhzhz24fw85CSz2irtN9w9HshBK7AQAAA==)...
87+
88+
```svelte
89+
let items = $state([...]);
90+
91+
let index = $state(0);
92+
let selected = $derived(items[index]);
93+
```
94+
95+
...you can change (or `bind:` to) properties of `selected` and it will affect the underlying `items` array. If `items` was _not_ deeply reactive, mutating `selected` would have no effect.
96+
5597
## Update propagation
5698

5799
Svelte uses something called _push-pull reactivity_ — when state is updated, everything that depends on the state (whether directly or indirectly) is immediately notified of the change (the 'push'), but derived values are not re-evaluated until they are actually read (the 'pull').

documentation/docs/02-runes/04-$effect.md

+2
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,8 @@ In general, `$effect` is best considered something of an escape hatch — useful
254254

255255
> [!NOTE] For things that are more complicated than a simple expression like `count * 2`, you can also use `$derived.by`.
256256
257+
If you're using an effect because you want to be able to reassign the derived value (to build an optimistic UI, for example) note that [deriveds can be directly overridden]($derived#Overriding-derived-values) as of Svelte 5.25.
258+
257259
You might be tempted to do something convoluted with effects to link one value to another. The following example shows two inputs for "money spent" and "money left" that are connected to each other. If you update one, the other should update accordingly. Don't use effects for this ([demo](/playground/untitled#H4sIAAAAAAAACpVRy26DMBD8FcvKgUhtoIdeHBwp31F6MGSJkBbHwksEQvx77aWQqooq9bgzOzP7mGTdIHipPiZJowOpGJAv0po2VmfnDv4OSBErjYdneHWzBJaCjcx91TWOToUtCIEE3cig0OIty44r5l1oDtjOkyFIsv3GINQ_CNYyGegd1DVUlCR7oU9iilDUcP8S8roYs9n8p2wdYNVFm4csTx872BxNCcjr5I11fdgonEkXsjP2CoUUZWMv6m6wBz2x7yxaM-iJvWeRsvSbSVeUy5i0uf8vKA78NIeJLSZWv1I8jQjLdyK4XuTSeIdmVKJGGI4LdjVOiezwDu1yG74My8PLCQaSiroe5s_5C2PHrkVGAgAA)):
258260

259261
```svelte

packages/svelte/src/compiler/phases/2-analyze/visitors/shared/utils.js

+1-30
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,6 @@ export function validate_assignment(node, argument, state) {
2121
const binding = state.scope.get(argument.name);
2222

2323
if (state.analysis.runes) {
24-
if (binding?.kind === 'derived') {
25-
e.constant_assignment(node, 'derived state');
26-
}
27-
2824
if (binding?.node === state.analysis.props_id) {
2925
e.constant_assignment(node, '$props.id()');
3026
}
@@ -38,25 +34,6 @@ export function validate_assignment(node, argument, state) {
3834
e.snippet_parameter_assignment(node);
3935
}
4036
}
41-
if (
42-
argument.type === 'MemberExpression' &&
43-
argument.object.type === 'ThisExpression' &&
44-
(((argument.property.type === 'PrivateIdentifier' || argument.property.type === 'Identifier') &&
45-
state.derived_state.some(
46-
(derived) =>
47-
derived.name === /** @type {PrivateIdentifier | Identifier} */ (argument.property).name &&
48-
derived.private === (argument.property.type === 'PrivateIdentifier')
49-
)) ||
50-
(argument.property.type === 'Literal' &&
51-
argument.property.value &&
52-
typeof argument.property.value === 'string' &&
53-
state.derived_state.some(
54-
(derived) =>
55-
derived.name === /** @type {Literal} */ (argument.property).value && !derived.private
56-
)))
57-
) {
58-
e.constant_assignment(node, 'derived state');
59-
}
6037
}
6138

6239
/**
@@ -81,7 +58,6 @@ export function validate_no_const_assignment(node, argument, scope, is_binding)
8158
} else if (argument.type === 'Identifier') {
8259
const binding = scope.get(argument.name);
8360
if (
84-
binding?.kind === 'derived' ||
8561
binding?.declaration_kind === 'import' ||
8662
(binding?.declaration_kind === 'const' && binding.kind !== 'each')
8763
) {
@@ -96,12 +72,7 @@ export function validate_no_const_assignment(node, argument, scope, is_binding)
9672
// );
9773

9874
// TODO have a more specific error message for assignments to things like `{:then foo}`
99-
const thing =
100-
binding.declaration_kind === 'import'
101-
? 'import'
102-
: binding.kind === 'derived'
103-
? 'derived state'
104-
: 'constant';
75+
const thing = binding.declaration_kind === 'import' ? 'import' : 'constant';
10576

10677
if (is_binding) {
10778
e.constant_binding(node, thing);

packages/svelte/tests/compiler-errors/samples/runes-no-derived-assignment/_config.js

-8
This file was deleted.

packages/svelte/tests/compiler-errors/samples/runes-no-derived-assignment/main.svelte

-5
This file was deleted.

packages/svelte/tests/compiler-errors/samples/runes-no-derived-binding/_config.js

-8
This file was deleted.

packages/svelte/tests/compiler-errors/samples/runes-no-derived-binding/main.svelte

-6
This file was deleted.

packages/svelte/tests/compiler-errors/samples/runes-no-derived-state-field-assignment/_config.js

-8
This file was deleted.

packages/svelte/tests/compiler-errors/samples/runes-no-derived-state-field-assignment/main.svelte

-10
This file was deleted.

packages/svelte/tests/compiler-errors/samples/runes-no-derived-state-field-update/_config.js

-8
This file was deleted.

packages/svelte/tests/compiler-errors/samples/runes-no-derived-state-field-update/main.svelte

-10
This file was deleted.

packages/svelte/tests/compiler-errors/samples/runes-no-derived-update/_config.js

-8
This file was deleted.

packages/svelte/tests/compiler-errors/samples/runes-no-derived-update/main.svelte

-5
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { flushSync } from 'svelte';
2+
import { test } from '../../test';
3+
4+
export default test({
5+
html: `
6+
<input type="range"><input type="range"><p>0 * 2 = 0</p>
7+
`,
8+
9+
ssrHtml: `
10+
<input type="range" value="0"><input type="range" value="0"><p>0 * 2 = 0</p>
11+
`,
12+
13+
test({ assert, target, window }) {
14+
const [input1, input2] = target.querySelectorAll('input');
15+
16+
flushSync(() => {
17+
input1.value = '10';
18+
input1.dispatchEvent(new window.Event('input', { bubbles: true }));
19+
});
20+
21+
assert.htmlEqual(
22+
target.innerHTML,
23+
`<input type="range"><input type="range"><p>10 * 2 = 20</p>`
24+
);
25+
26+
flushSync(() => {
27+
input2.value = '99';
28+
input2.dispatchEvent(new window.Event('input', { bubbles: true }));
29+
});
30+
31+
assert.htmlEqual(
32+
target.innerHTML,
33+
`<input type="range"><input type="range"><p>10 * 2 = 99</p>`
34+
);
35+
36+
flushSync(() => {
37+
input1.value = '20';
38+
input1.dispatchEvent(new window.Event('input', { bubbles: true }));
39+
});
40+
41+
assert.htmlEqual(
42+
target.innerHTML,
43+
`<input type="range"><input type="range"><p>20 * 2 = 40</p>`
44+
);
45+
}
46+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<script>
2+
let count = $state(0);
3+
let double = $derived(count * 2);
4+
</script>
5+
6+
<input type="range" bind:value={count} />
7+
<input type="range" bind:value={double} />
8+
9+
<p>{count} * 2 = {double}</p>

packages/svelte/tests/validator/samples/reassign-derived-literal/errors.json

-14
This file was deleted.

packages/svelte/tests/validator/samples/reassign-derived-literal/input.svelte

-9
This file was deleted.

packages/svelte/tests/validator/samples/reassign-derived-private-field/errors.json

-14
This file was deleted.

packages/svelte/tests/validator/samples/reassign-derived-private-field/input.svelte

-9
This file was deleted.

packages/svelte/tests/validator/samples/reassign-derived-public-field/errors.json

-14
This file was deleted.

packages/svelte/tests/validator/samples/reassign-derived-public-field/input.svelte

-9
This file was deleted.

0 commit comments

Comments
 (0)