skip to content

When would you deliberately change a SwiftUI view's id(_:) value to reset it, and what side effects come with that reset?

level: seniorimportance: should knowfreq 46%

answer

  1. new value, new view
  2. state derived from an input once
  3. everything inside starts over
  4. appear, task and animation effects
  5. never a value made in body

basics

~20 s

Change id(_:) when state derived once from an input must start over as that input changes, like a per-conversation composer. The reset is total: state, focus and owned models restart, onAppear and task run again, and inner changes don't animate.

solid answer

~40 s

`id(_:)` binds a view's identity to a `Hashable` value; when the value changes, Apple's documentation says the identity, and with it the state, is reset. That is the right tool when a subtree's state is derived from an input once, because a new input alone keeps the old state: `ComposerView(conversation: selected).id(selected.id)` gives each conversation a fresh composer. The reset is all-or-nothing: `@State`, `@FocusState` and `@GestureState` return to their initial values, owned models such as a `StateObject` are created again, `onAppear` runs for the new view, and an unfinished `task` is cancelled while the new view starts its own. The documentation also says SwiftUI doesn't automatically animate changes inside a view whose identity changes at the same time. Never pass a value that changes on every update, such as `UUID()`, or the view resets constantly.

code

swift · 27 lines
swift
struct Conversation: Identifiable {
    let id: String
    let title: String
}

struct ComposerView: View {
    let conversation: Conversation
    @State private var draft = ""
    @FocusState private var isFocused: Bool

    var body: some View {
        TextField("Message \(conversation.title)", text: $draft)
            .focused($isFocused)
            .onAppear { isFocused = true }
    }
}

struct ChatDetail: View {
    let selected: Conversation

    var body: some View {
        // A new conversation ID is a new composer: the draft empties,
        // focus state resets and onAppear runs again.
        ComposerView(conversation: selected)
            .id(selected.id)
    }
}

go deeper

for a junior

Recall that id(_:) takes any Hashable value and that changing the value makes SwiftUI treat the view as new, with fresh state.

for a middle

Explain the documented effects of a reset: all state wrappers restart, owned models are rebuilt, onAppear runs, unfinished tasks are cancelled, and inner changes don't animate.

for a senior

Choose a reset only when most of a subtree should start over, pick an ID that changes exactly when it should, and reach for onChange, task(id:) or hoisted state when only part should.

for a principal

Weigh resets as a component contract: document which shared views reset on which inputs, because an ID keyed too broadly silently costs work and user input across many screens.

## What `id(_:)` does `id(_:)` is a `View` modifier declared as `func id<ID>(_ id: ID) -> some View where ID : Hashable`, available since iOS 13. Apple's documentation describes it as binding a view's identity to the given proxy value, and says that when the value changes, the identity of the view (for example, its state) is reset. So `id(_:)` is SwiftUI's switch for "this is a different view now". Changing the value is not an update of the existing view; it ends that view and starts a new one at the same place. ## When a reset is the right tool A deliberate reset fits when a subtree's state is **derived from an input once** and should start over when that input changes: - **A composer per conversation.** A chat screen shows one `ComposerView` for the selected conversation. The draft, the focus and any attachment picker state belong to that conversation; switching conversations should start clean. `.id(selected.id)` does that in one line. - **Re-creating an owned model.** Apple's `StateObject` documentation has a section on forcing reinitialization by changing view identity: SwiftUI does not create a new object when a view's inputs change, but does when its identity changes, and it shows `.id(name)` as the way to tie the two together. - **Several inputs at once.** The same documentation combines two inputs with a `Hasher` and passes the resulting hash to `id(_:)`, so either input changing produces a new view. - **Discarding a half-finished form** after it is saved, by changing an ID the form is keyed on. ## What the reset costs | Effect | What you see | |---|---| | `@State`, `@FocusState`, `@GestureState` reset | Drafts empty, focus is lost, in-progress gesture values return to their start | | Owned models created again | A `StateObject` or a model held in `@State` is rebuilt | | `onDisappear` then `onAppear` | Appearance work runs again | | Unfinished `task` cancelled | The new view starts its own task, so loads repeat | | No in-place animation inside | The documentation says inner changes are not automatically animated when identity changes at the same time | | Subtree rebuilt | Everything under the view is created again | Apple's documentation sums this up: be mindful of the performance cost of reinitializing, and changing identity can have side effects, because it resets all state held by the view. ## Pitfalls 1. **`.id(UUID())` in `body`.** A new value on every evaluation gives the view a new identity on every update, so it resets constantly and its subtree is rebuilt each time. 2. **An ID that changes too often.** Keying a form on a hash of the whole model resets it on every keystroke that changes the model. Key it on the record's ID. 3. **Resetting a large subtree to fix one value.** If only one field must follow the input, updating that field is cheaper than recreating everything around it. 4. **Hiding a modelling problem.** If a reset is needed on every input change, the value may belong in the parent and should be passed down instead of copied into the child's state. ## Alternatives to a full reset - **Update one value when an input changes.** `onChange(of:initial:_:)`, the iOS 17 form with the value-carrying closures, can reset a single field; the lesson on appearance and async work covers it. - **Restart only the async work.** `task(id:)` cancels and restarts its task when its value changes, without resetting the view's state; the same lesson covers it. - **Hoist the state.** When the parent owns the value and passes it down, the child never needs a reset. ## Choosing between them In the chat app, the composer is keyed on the conversation ID because its draft, its focus and its attachment state all belong to one conversation. The message list beside it is not: switching conversations changes its data, and its rows already get their own identities from `ForEach`, so giving the whole list a new ID would only throw away work that the row IDs already handle. A full identity reset is the clearest choice when **almost everything** in the subtree should start over, which is common for per-item editors and composers. When only part of it should, prefer the narrower tools above, and keep the ID value something that changes only when the user would agree the view is "a different one".

  • How do you reset a subtree when either of two inputs changes?
    Derive one `Hashable` value from both and pass it to `id(_:)`. Apple's `StateObject` documentation does this with a `Hasher`: it combines the two inputs, calls `finalize()` and passes the hash, so a change to either produces a new identity. A small `Hashable` struct holding both inputs works the same way and avoids relying on a hash value.
  • When is task(id:) a better choice than changing id(_:)?
    When only the async work should restart. `task(id:)` cancels and restarts its task when its value changes, but the view keeps its identity, so its state, focus and owned models survive and inner changes can still animate. Changing `id(_:)` is for the case where the whole subtree should start over.

  • Passing .id(UUID()) in body is a harmless way to force a refresh
  • Changing id(_:) only re-runs body and keeps the view's @State
  • A new id(_:) value keeps @FocusState and only resets @State
  • id(_:) only accepts values from Identifiable types
  • Inner changes still animate in place when the view's identity changes