Skip to content

Commit 9aa92ae

Browse files
committed
fix: don't run each array expression more often than necessary
closes #14991 - at least to the extent possible Also adjusts a comment which a) did not hint at why it's needed in the first place (was added in #14967) b) sounded like we could change that in the future, but we can't, because people will always have the ability to trigger reactivity through other means without changing the array reference
1 parent ab3290f commit 9aa92ae

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

.changeset/tidy-months-rush.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: don't run each array expression more often than necessary

packages/svelte/src/internal/client/dom/blocks/each.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,15 +136,17 @@ export function each(node, flags, get_collection, get_key, render_fn, fallback_f
136136

137137
var was_empty = false;
138138

139-
// TODO: ideally we could use derived for runes mode but because of the ability
140-
// to use a store which can be mutated, we can't do that here as mutating a store
141-
// will still result in the collection array being the same from the store
139+
// We wrap this in a derived to ensure possible effects created as a result are associated with the derived,
140+
// rather than the each effect. Because people can mutate arrays and trigger reactivity through other means still,
141+
// we need to use derived_safe_equal.
142142
var each_array = derived_safe_equal(() => {
143143
var collection = get_collection();
144144

145145
return is_array(collection) ? collection : collection == null ? [] : array_from(collection);
146146
});
147147

148+
var first_run = true;
149+
148150
block(() => {
149151
var array = get(each_array);
150152
var length = array.length;
@@ -257,7 +259,10 @@ export function each(node, flags, get_collection, get_key, render_fn, fallback_f
257259
// that a mutation occurred and it's made the collection MAYBE_DIRTY, so reading the
258260
// collection again can provide consistency to the reactive graph again as the deriveds
259261
// will now be `CLEAN`.
260-
get(each_array);
262+
if (first_run) {
263+
first_run = false;
264+
get(each_array);
265+
}
261266
});
262267

263268
if (hydrating) {

0 commit comments

Comments
 (0)