How to manage view lifecycle events in SwiftUI
Discover SwiftUI's view lifecycle events onAppear, onDisappear, task, and task(id:).
updated on 15 Sep 2025 · 3 min read
When working with SwiftUI views, we often need to trigger side effects when a view appears or disappears. We can do that by using declarative modifiers that attach to views.

The onAppear(perform:) method
onAppear runs right before a view appears. It is useful for lightweight setup or triggering updates.
struct SomeView: View {var body: some View {VStack {...}.onAppear {viewModel.update()}}}
The onDisappear(perform:) method
onDisappear runs right after the view disappears. It's the place to clean up or cancel ongoing work.
struct SomeView: View {var body: some View {VStack {...}.onDisappear {viewModel.cancelLoading()}}}
The task(priority:_:) method
The task modifier allows us to start asynchronous work when a view appears. SwiftUI automatically cancels the task when the view disappears, so it integrates neatly with the view lifecycle.
struct SomeView: View {var body: some View {VStack {...}.task {await viewModel.load()}}}
The task(id:) variant
task(id:) is a more advanced form of task. It still behaves like the regular task in that it runs once when the view appears and is canceled when the view disappears. The difference is that it also observes a value we provide as an identifier. Whenever that value changes, SwiftUI cancels the old task and starts a new one automatically.
.task(id: viewModel.query) {await viewModel.search(query: viewModel.query)}
In this example, the search runs once when the view appears, and then again every time the query changes. This makes task(id:) especially useful for scenarios like search bars or dynamic filters, where you want to restart asynchronous work when a parameter updates, without having to manage cancellation manually.
With these tools, SwiftUI provides a clear way to run both synchronous and asynchronous work in response to view lifecycle changes.



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



