Why does SwiftUI reset view state on layout or parent updates?
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:
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) }
}- Why does the
if/elsebranch resetEditorViewstate, and why does@ObservedObjectrecreatevmon parent redraws? - Fix both bugs, and explain how
@Statewith@Observablediffers from@StateObjectand why unstableForEachIDs break list state.
Show hints (3)
- "CHECK STRUCTURAL IDENTITY"
SwiftUI gives the
trueandfalsebranches of anif/elsetwo distinct structural identities. TogglingisCompactdestroys the oldEditorViewand builds a new one. - "CHECK MODEL OWNERSHIP"
NotesScreenreadsunreadCountinbody, so every tick rebuildsEditorView.@ObservedObjectdoes not ownvm, so= EditorViewModel()replaces it on every redraw. - "KEEP ONE VIEW"
Apply
.padding(isCompact ? 0 : 16)to oneEditorView(), and use@StateObject(or@Statewith@Observableand a cheapinit(), since@Stateis 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.
| pattern | init() calls (mount + 3 redraws) | state resets | when to use |
|---|---|---|---|
@ObservedObject var vm = ... | 4 (replaces stored vm) | 3 | never instantiate inline |
@StateObject private var vm = ... | 1 (@autoclosure) | 0 | view owns ObservableObject |
@State private var vm = ... | 4 (3 temp copies dropped) | 0 | view owns @Observable (cheap init()) |
@ObservedObject var vm: VM | 0 (owned by parent) | 0 | child borrows parent's model |
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/elsejust to add a modifier like.padding()or.opacity(). That splits structural identity and resets child@State, animations, and keyboard focus. - Initializing
= MyViewModel()inside an@ObservedObjectproperty. Every parent redraw creates a new object, wiping unsaved edits and restarting active requests. - Running heavy work or network calls inside an
@Observableclassinit()owned by@State. BecauseState.init(wrappedValue:)is not@autoclosure, SwiftUI runsinit()on every parent redraw. - Using
ForEach(items, id: \.self)for duplicate strings or mutable models, or computingvar 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
1preserved instance (0resets), and@Observabletracks only properties actually read inbody. Unlike@StateObject, however,@Statedoes not wrap its initializer in@autoclosure, so SwiftUI evaluatesEditorViewModel()on every redraw and discards the temporary copy. Keepinit()cheap or initialize an optional@Statein.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@StateObjectcleanly. - "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 from0to16.
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 →