How to use EnvironmentObject correctly

Hi, I just learned SwiftUI and am still confused on how using @EnvironmentObject correctly. should I declare @StateObject to use @EnvironmentObject on later views or not? Or maybe I can directly declare the used file in the .environmentObject property?

like this?:

struct ContentView: View {
    @StateObject var viewModel = ViewModel()
    
    var body: some View {
        NavigationView {
              // Content
        }
        .environmentObject(viewModel)
    }
}

or this?:

struct ContentView: View {
    let viewModel = ViewModel()
    
    var body: some View {
        NavigationView {
              // Content
        }
        .environmentObject(viewModel)
    }
}

or maybe this?:

struct ContentView: View {
    var body: some View {
        NavigationView {
              // Content
        }
        .environmentObject(ViewModel())
    }
}

or these 3 actually works fine for different situations?

Accepted Answer

The first option is the recommended way of doing it.

  1. Create the ObservableObject class as an @StateObject property first, and only once
  2. Pass it into the environment, with environmentObject(_:)
  3. Access the class from subviews using @EnvironmentObject

Apparently I missed this article https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app smh (I think I’ve read it before but didn’t understand well)

How to use EnvironmentObject correctly
 
 
Q