pysxLearn by building

Compose an interface · Lesson 10 of 28

Stable keys and retained identity

Keep a draft, component state and keyboard focus attached to the same record.

A key tells reconciliation which record survived an update. If you key by position, the first slot stays the first slot even when a different record moves into it. A stable record key lets the existing DOM and its local state move together.

Record identity and record value are separate. A same-key replacement can rename a row without discarding its input or callbacks. Removing a key, however, ends that row's ownership; restoring the same key later starts a fresh lifetime.

Understand the moving parts

The demo uses component-local state inside each keyed row. Edit the first draft and use Focus and reverse, which focuses its owned input before changing order. The node should move instead of being recreated.

This is a behavioral contract worth testing with object identity, not just matching visible strings. An implementation can reconstruct identical HTML while still losing caret position, selection or a native control's state.

Walk through the code

from dataclasses import dataclass
from pysx import Dom, Fragment, each, local_state, pysx, signal


@dataclass(frozen=True)
class Row:
    key: str
    label: str


def app() -> Fragment:
    initial = (Row("alpha", "Alpha"), Row("beta", "Beta"))
    rows = signal(list(initial))
    dom = Dom()

    def row(item: Row) -> Fragment:
        draft = local_state("draft", "")
        count = local_state("count", 0)
        ref = dom.ref()

        def increment(_: object) -> None:
            count.update(lambda value: value + 1)

        async def move(_: object) -> None:
            await ref.handle().focus()
            rows.update(lambda values: list(reversed(values)))

        return pysx(t"""
            li(data-row={item.key})
                label(for={"draft-" + item.key}): {item.label}
                input(id={"draft-" + item.key} ref={ref} bindValue={draft})
                div:
                    button(data-increment={item.key} onClick={increment}): "Count:
                        " {count}
                    button(data-move={item.key} onClick={move}): "Focus and reverse"
        """)

    def remove(_: object) -> None:
        rows.update(lambda values: [item for item in values if item.key != "alpha"])

    def restore(_: object) -> None:
        if not any(item.key == "alpha" for item in rows()):
            rows.update(lambda values: [initial[0], *values])

    return pysx(t"""
        ul(id="keyed-rows"): {each(rows, row, key=lambda item: item.key)}
        div:
            button(id="row-remove" onClick={remove}): "Remove Alpha"
            button(id="row-restore" onClick={restore}): "Restore Alpha"
    """)

Row.key is alpha or beta, independent of position. Each row owns its draft, count and DOM ref. Focus and reverse moves surviving rows; removing Alpha disposes its local state, so restoration starts with an empty draft and zero count.

Try it live

Type into Alpha, increment its count, focus and reverse, then remove and restore Alpha.

What to observe

Movement keeps the draft/count/focus. Removal followed by restoration creates an empty draft.

Take this with you

Keys preserve surviving identities; they do not resurrect a disposed component.