tezvyn:

View identity in SwiftUI and the .id() modifier

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

how SwiftUI tracks views across updates.

OUTLINE

identity links a view to its persistent state and transitions; structural identity comes from position, explicit identity from .id(); changing the id resets state and forces a new view.

WHY IT EXISTS SwiftUI rebuilds view value structs constantly, so it needs a stable notion of which view is which across updates to decide what keeps its state, what animates, and what is created or destroyed. That notion is identity.

THE MENTAL MODEL A view's identity, not its struct value, links it to persistent state such as @State and @StateObject, to lifecycle callbacks like onAppear, and to transition animations. Two kinds of identity exist. Structural identity comes from the view's position in the view hierarchy, including branches of conditionals and positions in a ForEach. Explicit identity is what you assign with .id() or the id parameter of ForEach.

HOW IT WORKS When SwiftUI diffs an update, a view that keeps the same identity keeps its state and is merely reconfigured. A view whose identity changes is treated as a removal of the old view and insertion of a new one, so its @State resets and transitions fire. The .id() modifier lets you set identity explicitly: pass a value that stays constant to preserve state, or pass a value that changes to force a fresh view.

WHEN IT MATTERS Use a stable id in ForEach so reordering animates correctly instead of scrambling state. Attach .id(someToken) to force a reset, for example to clear a form or restart an animation when a token changes. Misusing it, such as giving rows array indices that shift, causes state to attach to the wrong row.

COMMON WRONG ANSWERS Thinking identity equals Equatable on the view struct. Believing .id() is only a list helper. Using array indices as ForEach ids in a mutable list.

ONE CONCRETE EXAMPLE A detail screen shows fields for the selected user, but switching users leaves stale text because the same view instance keeps its @State. Adding .id(user.id) gives the view a new identity per user, so SwiftUI tears down the old view, resets its state, and animates in fresh fields for each selection.

Read the original → dev.to

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.