How do I perform side effects with task, onAppear, and onChange?

In SwiftUI, `task`, `onAppear`, and `onChange` modifiers allow you to perform side effects in your views such as fetching data or responding to state changes. Each method has its purpose and scope of execution.

Using `task` Modifier

The `task` modifier is used to run asynchronous tasks when a view appears. This is particularly useful for data-fetching operations that should start when the view is presented.

Using `onAppear` Modifier

The `onAppear` modifier executes code every time the view appears. It's a great place to start animations or log data events.

Using `onChange` Modifier

The `onChange` modifier allows you to respond to specific state changes in your view. It's useful for executing logic when a value changes.

Example Code

// Example of using task, onAppear, and onChange in SwiftUI struct ContentView: View { @State private var data: String = "Initial Data" @State private var shouldFetchData: Bool = false var body: some View { Text(data) .onAppear { // Perform side effect: fetch initial data loadData() } .onChange(of: shouldFetchData) { newValue in // Perform side effect: fetch data when flag changes if newValue { loadData() } } .task { // Perform asynchronous side effect await fetchData() } } func loadData() { data = "Data Loaded" } func fetchData() async { // Simulate fetching data await Task.sleep(2 * 1_000_000_000) // Sleep for 2 seconds data = "Fetched Data" } }

SwiftUI task onAppear onChange side effects view lifecycle