Skip to content

Instantly share code, notes, and snippets.

View aclima93's full-sized avatar
💭
Including Bugs

António Lima aclima93

💭
Including Bugs
View GitHub Profile
@aclima93
aclima93 / swiftui-state.markdown
Created March 10, 2023 09:56 — forked from gdavis/swiftui-state.markdown
Swift UI State Management

Swift UI State Management

Storing state for Child View Models

SwiftUI is all about state, and maintaining that state can be rather difficult when you have more than a few properties stored as @State for your view. It is common practice to use a view model to store the state outside of the view, since our views are constantly recreated as our state changes. Keeping what state you want in memory can provide a challenge, much more so than it may seem at first glance.

With SwiftUI 2, using @StateObject will keep a view model from being recreated with each rendering of a view's body. If the parent view is creating the view model, and then passing that down to the child view, that view model will also be recreated with each rendering of that parent view body.

struct ParentView: View {
  var body: some View {