diff --git a/.changeset/nine-vans-admire.md b/.changeset/nine-vans-admire.md new file mode 100644 index 0000000000..5ede9fdbbf --- /dev/null +++ b/.changeset/nine-vans-admire.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +chore: improve derived ownership model diff --git a/packages/svelte/src/internal/client/reactivity/deriveds.js b/packages/svelte/src/internal/client/reactivity/deriveds.js index b273e4c518..a5678f1d68 100644 --- a/packages/svelte/src/internal/client/reactivity/deriveds.js +++ b/packages/svelte/src/internal/client/reactivity/deriveds.js @@ -31,7 +31,7 @@ import { inspect_effects, set_inspect_effects } from './sources.js'; */ /*#__NO_SIDE_EFFECTS__*/ export function derived(fn) { - let flags = DERIVED | DIRTY; + var flags = DERIVED | DIRTY; if (active_effect === null) { flags |= UNOWNED; @@ -58,9 +58,6 @@ export function derived(fn) { var derived = /** @type {Derived} */ (active_reaction); (derived.children ??= []).push(signal); } - if (active_effect !== null) { - (active_effect.deriveds ??= []).push(signal); - } return signal; } diff --git a/packages/svelte/src/internal/client/runtime.js b/packages/svelte/src/internal/client/runtime.js index 6786d99d90..0416934ee9 100644 --- a/packages/svelte/src/internal/client/runtime.js +++ b/packages/svelte/src/internal/client/runtime.js @@ -801,10 +801,17 @@ export function get(signal) { set_signal_status(active_effect, DIRTY); schedule_effect(active_effect); } + } else if (is_derived) { + var derived = /** @type {Derived} */ (signal); + var parent = derived.parent; + + if (parent !== null && !parent.deriveds?.includes(derived)) { + (parent.deriveds ??= []).push(derived); + } } if (is_derived) { - var derived = /** @type {Derived} */ (signal); + derived = /** @type {Derived} */ (signal); if (check_dirtiness(derived)) { update_derived(derived); diff --git a/packages/svelte/tests/signals/test.ts b/packages/svelte/tests/signals/test.ts index 4dffd8e962..e2d27267a3 100644 --- a/packages/svelte/tests/signals/test.ts +++ b/packages/svelte/tests/signals/test.ts @@ -488,7 +488,6 @@ describe('signals', () => { assert.equal(a?.deps?.length, 1); assert.equal(s?.reactions?.length, 1); destroy(); - assert.equal(a?.deps, null); assert.equal(s?.reactions, null); }; });