@EnvironmentObject in Views May Not be a Good Idea But Avoiding Them is Probably Much Worse
@EnvironmentObject allows you to create global state that can be shared and manipulated from any view in your application. We tend to put @EnvironmentObject in our views and directly access the global state. This creates a tight coupling between the view and the
@EnvironmentObject, but avoiding this approach opens up a whole new cans of worms. In this article, I will discuss how @EnvironmentObject can be used in a SwiftUI view and how avoiding can create dependency injection nightmare.
EnvironmentObject Counter Example:
Let’s create a simple counter example. Our app will consists of three views. The ContentView will be the parent view, which will host IncrementCounterView and DisplayCounterView. IncrementCounterView will increment the global state counter value and DisplayCounterView will display the value from the global state.
The global state class
AppState is shown below:
The AppState class conforms to the
ObservableObject protocol and it consists of a single property called value. The value property is responsible for keeping track of the counter. The
@Published property wrapper allows to publish the changes to the value property, which can be used by the view to render themselves.
The ContentView acts as the root of the application and host our other child views.
Each child view uses
@EnvironmentObject to access the global state.