download

Why does SwiftUI reset view state on layout or parent updates?

Mobile~8 minReviewed 3 Dec 2026Free · No sign-in

Question

A SwiftUI notes screen has two state bugs. Toggling isCompact clears cursor focus and wipes EditorView's local @State. Worse, whenever unreadCount ticks every 5 seconds (3 times in 15 seconds), EditorView resets its text to empty:

"SWIFT"
struct NotesScreen: View {
    @State private var isCompact = false
    @State private var unreadCount = 0
    var body: some View {
        VStack {
            Text("Unread: \(unreadCount)")
            if isCompact { EditorView() }
            else { EditorView().padding(16) }
        }
    }
}

struct EditorView: View {
    @ObservedObject var vm = EditorViewModel()
    var body: some View { TextEditor(text: $vm.body) }
}
  1. Why does the if/else branch reset EditorView state, and why does @ObservedObject recreate vm on parent redraws?
  2. Fix both bugs, and explain how @State with @Observable differs from @StateObject and why unstable ForEach IDs break list state.
Show hints (3)
  1. "CHECK STRUCTURAL IDENTITY"

    SwiftUI gives the true and false branches of an if/else two distinct structural identities. Toggling isCompact destroys the old EditorView and builds a new one.

  2. "CHECK MODEL OWNERSHIP"

    NotesScreen reads unreadCount in body, so every tick rebuilds EditorView. @ObservedObject does not own vm, so = EditorViewModel() replaces it on every redraw.

  3. "KEEP ONE VIEW"

    Apply .padding(isCompact ? 0 : 16) to one EditorView(), and use @StateObject (or @State with @Observable and a cheap init(), since @State is not @autoclosure).

Show checked explanation

if isCompact { EditorView() } else { EditorView().padding(16) } assigns two distinct structural identities, so toggling isCompact destroys EditorView and wipes its state. Keep one EditorView() and vary .padding(isCompact ? 0 : 16). Own vm with @StateObject (@autoclosure, 1 allocation, 0 resets) or @State with @Observable (0 resets, eager init() on redraws) instead of inline @ObservedObject.

SwiftUI structural identity transitions, ObservedObject vs StateObject (@autoclosure) vs State(@Observable eager init) allocation and reset counts across parent redraws, and ForEach ID stability were simulated on CPython 3.12.10 (no SwiftUI or Xcode runtime installed locally); SwiftUI state and identity APIs checked against official Apple documentation. Checked by an editor other than the author.

Walkthrough

SwiftUI ties every @State and @StateObject storage slot to a view's identity, not to a View struct instance. Because NotesScreen.body reads unreadCount, each 5-second tick re-evaluates body and builds a fresh EditorView struct.

Bug 1 (structural identity): An if/else compiles into _ConditionalContent<TrueView, FalseView>. SwiftUI treats those two branches as unrelated views. Toggling isCompact tears down the old EditorView, wipes its state, and mounts a new one. Keeping one EditorView() with .padding(isCompact ? 0 : 16) preserves identity across toggles.

Bug 2 (ownership and init timing): @ObservedObject only borrows a model owned elsewhere. Over mount plus 3 redraws, @ObservedObject var vm = EditorViewModel() runs 4 allocations and resets vm 3 times, wiping unsaved text. @StateObject uses @autoclosure, creating vm once (1 allocation, 0 resets). On iOS 17+, @State private var vm = EditorViewModel() with @Observable also keeps 1 stored instance (0 resets). However, State.init(wrappedValue:) is not @autoclosure, so SwiftUI still runs EditorViewModel() on every redraw (4 allocations) and drops the 3 temporary copies. Keep @Observable init() cheap, or create it lazily in .task.

patterninit() calls (mount + 3 redraws)state resetswhen to use
@ObservedObject var vm = ...4 (replaces stored vm)3never instantiate inline
@StateObject private var vm = ...1 (@autoclosure)0view owns ObservableObject
@State private var vm = ...4 (3 temp copies dropped)0view owns @Observable (cheap init())
@ObservedObject var vm: VM0 (owned by parent)0child borrows parent's model
"SWIFT"
struct NotesScreen: View {
    @State private var isCompact = false
    @State private var unreadCount = 0
    var body: some View {
        VStack {
            Text("Unread: \(unreadCount)")
            EditorView().padding(isCompact ? 0 : 16)
        }
    }
}

struct EditorView: View {
    @StateObject private var vm = EditorViewModel()
    var body: some View { TextEditor(text: $vm.body) }
}

Explicit list identity: In ForEach, id: \.self collides on duplicate values and changes identity whenever a mutable value edits. A computed UUID() mints fresh IDs on every redraw, wiping row state. Always conform items to Identifiable with a stable stored id.

Common mistakes

  • Branching with if/else just to add a modifier like .padding() or .opacity(). That splits structural identity and resets child @State, animations, and keyboard focus.
  • Initializing = MyViewModel() inside an @ObservedObject property. Every parent redraw creates a new object, wiping unsaved edits and restarting active requests.
  • Running heavy work or network calls inside an @Observable class init() owned by @State. Because State.init(wrappedValue:) is not @autoclosure, SwiftUI runs init() on every parent redraw.
  • Using ForEach(items, id: \.self) for duplicate strings or mutable models, or computing var id: UUID { UUID() } on the fly, which destroys row state on every redraw.

Follow-up questions

  • "How does @State with @Observable in iOS 17+ differ from @StateObject on parent redraws?" Both keep 1 preserved instance (0 resets), and @Observable tracks only properties actually read in body. Unlike @StateObject, however, @State does not wrap its initializer in @autoclosure, so SwiftUI evaluates EditorViewModel() on every redraw and discards the temporary copy. Keep init() cheap or initialize an optional @State in .task.
  • "When is resetting a child view's identity with .id(note.id) actually the right move?" Use .id(note.id) intentionally when switching to another record, such as picking a different note in a sidebar. SwiftUI then discards the old editor's local @State, scroll offset, and @StateObject cleanly.
  • "Why does SwiftUI allow inert modifiers like .padding(0) or .opacity(1) without extra runtime cost?" Because SwiftUI diffs lightweight modifier trees and keeps the same underlying view identity, preserving @State, text focus, and smooth implicit animations when values change from 0 to 16.

What a strong answer covers

Explains structural identity splitting across if/else, replaces the branch with .padding(isCompact ? 0 : 16), contrasts @ObservedObject resets with @StateObject (@autoclosure) and @State + @Observable (eager init(), 0 resets), and warns against unstable ForEach IDs.

Open in interactive practice deck →

Original OfferVibe question. Managing model data in your app · StateObject · ObservedObject · ForEach · Migrating to Observable.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.