Skip to content

Commit

Permalink
fix: don't run each array expression more often than necessary
Browse files Browse the repository at this point in the history
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
  • Loading branch information
dummdidumm committed Jan 13, 2025
1 parent ab3290f commit 9aa92ae
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/tidy-months-rush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: don't run each array expression more often than necessary
13 changes: 9 additions & 4 deletions packages/svelte/src/internal/client/dom/blocks/each.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,15 +136,17 @@ export function each(node, flags, get_collection, get_key, render_fn, fallback_f

var was_empty = false;

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

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

var first_run = true;

block(() => {
var array = get(each_array);
var length = array.length;
Expand Down Expand Up @@ -257,7 +259,10 @@ export function each(node, flags, get_collection, get_key, render_fn, fallback_f
// that a mutation occurred and it's made the collection MAYBE_DIRTY, so reading the
// collection again can provide consistency to the reactive graph again as the deriveds
// will now be `CLEAN`.
get(each_array);
if (first_run) {
first_run = false;
get(each_array);
}
});

if (hydrating) {
Expand Down

0 comments on commit 9aa92ae

Please sign in to comment.