DEV Community

Thomas Prezioso Jr.
Thomas Prezioso Jr.

Posted on

2

What’s the Difference between @ObservedObject and @StateObject in SwiftUI

@StateObject and @ObservedObject are very similar in that they both keep track of an objects state. The difference is @StateObject is owned by the view it was created in where as @ObservedObject is owned by another view.

An example of when to use @ObservedObject is to keep track of external classes so the view can be updated when a change occurs. We would want to use an @ObservedObject for something like fetching new data from an API or a database.

We want to use @StateObject when we want the view to keep track of its own objects state. A example of how we would use @StateObject is if we had something like a number counter in a view and we wanted to keep track of the count as the numbers changed.

I hope this helps you better understand the difference between when to use @ObservedObject and @StateObject.

For a deeper dive into @StateObject vs @ObservedObject checkout these great articles by Donny Wals and Swapnanil Dhol.

Thanks for reading and happy coding 👨🏻‍💻👨🏻‍💻👨🏻‍💻

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools 🔁

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay