How @State works?

Asked on 09/06/2024

1 search

In SwiftUI, @State is a property wrapper used to create an internal source of data for a view. When you mark a view property with @State, SwiftUI manages the storage and provides it back for the view to read and write. This allows the view to react to changes in the state and update the UI accordingly.

For example, in a view that allows you to rate a pet's tricks, @State can be used to keep track of the current rating. When the rating changes, SwiftUI automatically updates the UI to reflect the new value. This is achieved by SwiftUI calling the body of the view again with the updated state, which then returns a new view hierarchy that reflects the changes.

Additionally, SwiftUI provides a Binding to create a two-way reference to the state of another view. This is useful when you want to share state between different views, ensuring that they stay in sync.

For more details, you can refer to the SwiftUI essentials session at timestamp 10:41.