Blog / January 15, 2023 / 2 mins read / By Mahi Garg

@State: SwiftUI

In SwiftUI, a powerful framework for building user interfaces, managing and updating the state of our views is essential for creating dynamic and interactive user experiences. One key tool SwiftUI provides for this purpose is the @State property wrapper.

Now let us understand what is @State, how it works, what we can achieve through this, and much more.

What is @State?

The @State property wrapper is a fundamental component of SwiftUI that allows us to declare mutable state properties within a view. When the value of @State property changes, SwiftUI automatically re-renders the view, ensuring that the UI stays synchronized with the underlying state.

Let us understand this with an example.

Consider you want to change the background color of your view with a few button clicks. please have a look at the below code where we will understand its declaration and usage part as well.

struct stateBootCamp: View {
    
    @State var backgroundColor = Color.red
    
    var body: some View {
        ZStack {
            backgroundColor
            VStack(spacing: 20) {
                Text("Studing @State")
                    .font(.title)
                Button("BUTTON Green") {
                        backgroundColor = .green
                    }
                Button("BUTTON Pink") {
                        backgroundColor = .pink
                    }
                }
            .foregroundColor(.white)
        }
    }
}

To declare, prefix @State to property declaration. Above we made backgroundColor a state property.

Now let us understand it’s working.

@State: SwiftUI

The first view is your Initial View in zero state. When you tap on BUTTON Green, the background color changes to green as we are changing the state variable color to Green as the action of Button. Similarly, on Tap of BUTTON Pink, the background color changes to Pink. With this, we understood how @State is used.

Usage scenario of @State

@State is best suited for managing a state within a single view or a small portion of the view hierarchy. It works well for a local, transient state that doesn’t need to be shared across multiple views or persisted across sessions.

Limitation of @State

@State not suitable for managing states across multiple views or when sharing states between different parts of an application. In such cases, @ObservedObject or @EnvironmentObject maybe more appropriate choices. By leveraging @State, SwiftUI empowers developers to build modern, responsive applications that are efficient, maintainable, and delightful to use.

Comments