Lifetime of State Properties in SwiftUI
However, when you have worked with
@State
(or@StateObject
), you will notice that there might be some strange behavior. Sometimes your state disappears, especially when working with aList
(or to be precise: any view that usesForEach
directly or indirectly).[…]
List creates its subviews lazily.
[…]
The children of a
List
will be kept around. The lifetime of a@State
’s property is directly tied to the lifetime of a view. Once a list child is created, it never goes away again, unless the list goes away itself.[…]
It turns out that while the children of a
List
will be kept around (including their associated state), the bodies of those views will get destroyed. These will get recreated lazily once the view appears on screen again.