How to manage lifecycle events in SwiftUI iOS applications
Discover SwiftUI's lifecycle events onAppear(), onDisappear() and task().
26 Sep 2022 · 3 min read
When working with views in an iOS application, we often need to trigger side effects when certain lifecycle events occur - for example loading or refreshing some data when a view appears.
In UIKit, we did that by overriding methods like viewDidAppear(_:) or viewDidDisappear(_:).
SwiftUI also provides methods like onAppear(perform:), onDisappear(perform:) and task(priority:_:) to react to lifecycle events. Let's jump in and look at those methods in more detail.

The onAppear(perform:) method
The onAppear(perform:) method can be used to do some work right before the view appears - for example to setup some initial state.
struct SomeView: View {var body: some View {VStack {...}.onAppear {viewModel.update()}}}
The onDisappear(perform:) method
The onDisappear(perform:) method can be used to do some work right after the view disappears - for example to cancel running tasks.
struct SomeView: View {var body: some View {VStack {...}.onDisappear {viewModel.cancelLoading()}}}
The task(priority:_:) method
The task(priority:_:) method can be used to start some asynchronious work right before the view appears.
struct SomeView: View {var body: some View {VStack {...}.task {do {try await viewModel.load()} catch {...}}}}
Additionally, SwiftUI automatically cancels the task when the view disappears.
The onReceive(_:perform:) method
Not a SwiftUI view lifecycle method per se, the onReceive(_:perform:) method can be useful to react to application lifecycle events - for example to update a view when the app enters foreground.
struct SomeView: View {var body: some View {VStack {...}.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ inviewModel.update()}}}

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