Skip to content

Commit 0081950

Browse files
committed
fix: properly clean up component lifecycle order issue
- move effect cleanup to happen before new creation in key function - ensure proper lifecycle order. destroy old component -> create new component - so now the order is script -> mount -> abort -> destroy -> script -> mount
1 parent bde51ed commit 0081950

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

.changeset/chilled-donkeys-ring.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: fixed component lifecycle timing issue in #key blocks. its now properly cleaned up before new instance are created.

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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export function key(node, get_key, render_fn) {
2525
/** @type {V | typeof UNINITIALIZED} */
2626
var key = UNINITIALIZED;
2727

28-
/** @type {Effect} */
28+
/** @type {Effect | null} */
2929
var effect;
3030

3131
/** @type {Effect} */
@@ -37,10 +37,6 @@ export function key(node, get_key, render_fn) {
3737
var changed = is_runes() ? not_equal : safe_not_equal;
3838

3939
function commit() {
40-
if (effect) {
41-
pause_effect(effect);
42-
}
43-
4440
if (offscreen_fragment !== null) {
4541
// remove the anchor
4642
/** @type {Text} */ (offscreen_fragment.lastChild).remove();
@@ -54,6 +50,12 @@ export function key(node, get_key, render_fn) {
5450

5551
block(() => {
5652
if (changed(key, (key = get_key()))) {
53+
// Pause and cleanup the old effect before creating a new one
54+
// This ensures proper component lifecycle ordering (destroy -> create -> mount)
55+
if (effect) {
56+
pause_effect(effect);
57+
effect = null;
58+
}
5759
var target = anchor;
5860

5961
var defer = should_defer_append();
@@ -63,6 +65,7 @@ export function key(node, get_key, render_fn) {
6365
offscreen_fragment.append((target = create_text()));
6466
}
6567

68+
// Create the new effect with the component
6669
pending_effect = branch(() => render_fn(target));
6770

6871
if (defer) {

0 commit comments

Comments
 (0)