Created
October 31, 2019 22:44
-
-
Save chrisfsampaio/e20c394a64d9bc67e8081c9d099cd030 to your computer and use it in GitHub Desktop.
SwiftUI @EnvironmentObject unnecessary re-render
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
class State: ObservableObject { | |
@Published var counter: Int = 0 | |
} | |
struct ContentView: View { | |
var body: some View { | |
return ListView().environmentObject(State()) | |
} | |
} | |
struct ListView: View { | |
@EnvironmentObject var state: State | |
var body: some View { | |
NavigationView { | |
VStack(spacing: 36) { | |
NavigationLink(destination: DetailView()) { | |
Text("Push detail view") | |
} | |
Button(action: { | |
self.state.counter += 1 | |
}) { | |
Text("Change environment object") | |
} | |
} | |
} | |
} | |
} | |
struct DetailView: View { | |
@EnvironmentObject var state: State | |
var body: some View { | |
print("Render detail") | |
return Text("Counter: \(state.counter)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment