You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: sites/svelte-5-preview/src/routes/docs/content/01-api/02-runes.md
+12-18Lines changed: 12 additions & 18 deletions
Original file line number
Diff line number
Diff line change
@@ -250,40 +250,34 @@ $effect(() => {
250
250
});
251
251
```
252
252
253
-
An effect only reruns when the object it reads changes, not when a property inside it changes. If you want to react to _any_ change inside an object for inspection purposes at dev time, you may want to use [`inspect`](#$inspect).
253
+
An effect only reruns when the object it reads changes, not when a property inside it changes. (If you want to observe changes _inside_an object at dev time, you can use [`$inspect`](#$inspect).)
254
254
255
255
```svelte
256
256
<script>
257
-
let object = $state({ count: 0 });
258
-
let derived_object = $derived({
259
-
doubled: object.count * 2
260
-
});
257
+
let a = $state({ value: 0 });
258
+
let b = $derived({ value: a.value * 2 });
261
259
260
+
// this will run once, because `a` is never reassigned (only mutated)
262
261
$effect(() => {
263
-
// never reruns, because object does not change,
264
-
// only its property changes
265
-
object;
266
-
console.log('object');
262
+
a;
267
263
});
268
264
265
+
// this will run whenever `a.value` changes...
269
266
$effect(() => {
270
-
// reruns, because object.count changes
271
-
object.count;
272
-
console.log('object.count');
267
+
a.value;
273
268
});
274
269
270
+
// ...and so will this, because `b` is a new object each time
275
271
$effect(() => {
276
-
// reruns, because $derived produces a new object on each rerun
277
-
derived_object;
278
-
console.log('derived_object');
272
+
b;
279
273
});
280
274
</script>
281
275
282
-
<button onclick={() => object.count++}>
283
-
{derived_object.doubled}
276
+
<button onclick={() => (a.value += 1)}>
277
+
{a.value}
284
278
</button>
285
279
286
-
<p>{object.count} doubled is {derived_object.doubled}</p>
280
+
<p>{a.value} doubled is {b.value}</p>
287
281
```
288
282
289
283
You can return a function from `$effect`, which will run immediately before the effect re-runs, and before it is destroyed ([demo](/#H4sIAAAAAAAAE42SzW6DMBCEX2Vl5RDaVCQ9JoDUY--9lUox9lKsGBvZC1GEePcaKPnpqSe86_m0M2t6ViqNnu0_e2Z4jWzP3pqGbRhdmrHwHWrCUHvbOjF2Ei-caijLTU4aCYRtDUEKK0-ccL2NDstNrbRWHoU10t8Eu-121gTVCssSBa3XEaQZ9GMrpziGj0p5OAccCgSHwmEgJZwrNNihg6MyhK7j-gii4uYb_YyGUZ5guQwzPdL7b_U4ZNSOvp9T2B3m1rB5cLx4zMkhtc7AHz7YVCVwEFzrgosTBMuNs52SKDegaPbvWnMH8AhUXaNUIY6-hHCldQhUIcyLCFlfAuHvkCKaYk8iYevGGgy2wyyJnpy9oLwG0sjdNe2yhGhJN32HsUzi2xOapNpl_bSLIYnDeeoVLZE1YI3QSpzSfo7-8J5PKbwOmdf2jC6JZyD7HxpPaMk93aHhF6utVKVCyfbkWhy-hh9Z3o_2nQIAAA==)).
0 commit comments