skip to content

Lifecycle and Previews

The app and its scenes, the hooks where work starts and stops, and previews for design-time iteration. Interviewers ask why task beats onAppear and how to keep previews fast.

on this pageshow

explore

questions

16

In SwiftUI, when do onAppear and onDisappear run, and why can onAppear fire more than once for one screen?

level: juniorimportance: must knowfreq 65%

answer

  1. appearance, not creation
  2. before the first rendered frame
  3. a view's init is not an appearance
  4. pop back, switch tabs, scroll rows

basics

~20 s

onAppear runs its closure before a view appears on screen and onDisappear after it leaves; both follow appearance, not the view struct's init, so a screen shown again after navigation, a tab switch or scrolling can fire onAppear again.

solid answer

~40 s

`onAppear(perform:)` runs a synchronous closure before the view appears; Apple's documentation says it completes before the first rendered frame, though the exact moment depends on the view type. `onDisappear(perform:)` runs after the view has left the interface. Both follow what is on screen, not the life of the view struct: SwiftUI may run a view's `init` and `body` many times without an appearance, and one view can appear many times. Popping back to a screen in a `NavigationStack`, returning to a tab, or scrolling a `List` row back into view can all fire `onAppear` again. So guard one-time setup with state that survives, keep the closure short, and start async work with the `task` modifier instead.

go deeper

for a junior

Recall that onAppear runs before a view appears and onDisappear after it leaves, and that both closures are synchronous.

for a middle

Explain why appearance differs from a view struct's creation, and list the real cases where onAppear fires again: navigation, tabs, lazy rows, conditional content.

for a senior

Show how you make appearance-driven work idempotent and why you avoid depending on parent and child appear order, which the documentation does not promise.

for a principal

Frame the review rule a team needs: appearance hooks stay short and repeat-safe, and async work goes to task so the view's lifetime owns it.

## What the two modifiers promise `onAppear(perform:)` and `onDisappear(perform:)` are SwiftUI view modifiers that attach a plain, synchronous closure to a view's **appearance** in the interface. Apple's documentation describes them carefully: - `onAppear` adds an action to perform **before** the view appears. The exact moment depends on the kind of view it is attached to, but the closure **completes before the first rendered frame** appears. - `onDisappear` adds an action to perform **after** the view disappears. Again the exact moment depends on the view type, but the closure does not run until the view has left the interface. - Both closures are optional and take no arguments; passing `nil` makes the call have no effect. - Neither closure is `async`. You cannot `await` inside them directly. So the question each one answers is "is this view on screen now?", not "does this view exist?". ## Appearance is not creation A SwiftUI `View` is a lightweight struct that describes part of the interface. SwiftUI may create that struct, run its `init` and evaluate its `body` many times while the screen is updating, for example every time a parent's state changes. None of that is an appearance. Conversely, one view can appear, disappear and appear again many times over its life. This is why two common habits go wrong: - **Loading data in `init`.** The initializer can run repeatedly, including for views that are never shown, so side effects there repeat unpredictably. - **Treating `onAppear` as a constructor.** It is closer to a "became visible" notification than to a one-time setup hook. ## Why onAppear fires more than once `onAppear` runs again whenever the view appears again. Typical cases in a real app: 1. **Navigation.** A root screen in a `NavigationStack` disappears when a detail screen is pushed and can appear again when the user pops back. 2. **Tabs.** Switching away from a tab and back can make the tab's content disappear and reappear. 3. **Lazy containers.** In a `List` or a lazy stack, rows are created as they scroll into view; a row that scrolls out and back in can fire `onAppear` again. 4. **Conditional content.** An `if` that removes a view and later inserts it again produces a fresh appearance. 5. **A change of identity.** Giving a view a new identity, for instance with `id(_:)`, makes SwiftUI treat it as a different view, which appears anew. Each of these is legitimate, so the code inside must tolerate repetition: a one-time load either checks whether the data is already there, or lives somewhere that does not disappear. ## The order between parent and child Interviewers sometimes ask which fires first, a parent's `onAppear` or a child's. Apple's documentation only says the moment depends on the view type; it does not promise an order between ancestors and descendants. The safe answer is not to build logic that depends on that order. If a child needs data the parent loads, pass the data down or let the child show a placeholder until it arrives. ## Seeing it in practice A quick way to build intuition is to add a log line to `onAppear` and `onDisappear` on a stock-quote screen and then use the app: push a detail screen and pop back, switch tabs, scroll a long list of symbols. The log shows appearance events arriving in pairs as the screen leaves and returns, while a log line in the view's `init` may fire far more often and with no pairing at all. Seeing the two streams side by side is usually what makes the difference between creation and appearance click, and it shows which events a guard has to tolerate before the code ships. ## Choosing the right hook | Need | Modifier | Notes | |---|---|---| | Quick synchronous setup when shown | `onAppear(perform:)` | Runs on every appearance | | Clean-up when hidden | `onDisappear(perform:)` | Runs after the view leaves | | Async loading tied to the view | `task` | Cancelled after the view disappears | | React to a value, including the first one | `onChange(of:initial:_:)` with `initial: true` | iOS 17 and later | ## Practical rules - Keep `onAppear` closures short and synchronous: logging a screen view, setting focus, kicking off a cheap state update. - Never assume `onAppear` runs once. Guard one-time work with state that survives the disappearance, or move it higher in the hierarchy. - Do not start network calls with `Task { }` inside `onAppear`; the `task` modifier does that job and is cancelled for you. - Use `onDisappear` for clean-up that must follow the view leaving the screen, not for releasing memory; SwiftUI manages the view struct's storage itself. Read this way, the two modifiers are simple and predictable: they follow what is on screen, every time it changes.

  • How do you keep a one-time load from repeating when onAppear fires again?
    Make the load idempotent: skip it when the data is already in `@State` or in the model, or own the data in a view higher up that does not disappear. Moving the call to `task` helps with cancellation but not with repetition, because `task` also starts again when the view reappears.
  • How would you use onAppear to load the next page of a long List?
    Attach `onAppear` to the last row, or a sentinel row after it, and request the next page when it appears. Because rows can appear repeatedly as the user scrolls, keep an `isLoadingPage` flag and the last loaded page in state so duplicate appearances do not fire duplicate requests. On iOS 18 and later, scroll-visibility modifiers are an alternative covered with scroll views.

  • onAppear runs exactly once, when the view struct is created, like a constructor.
  • A view's init runs once per screen, so it is a safe place to start loading.
  • You can await network calls directly inside an onAppear closure.
  • A parent's onAppear is guaranteed to run after all its children's, so code can rely on it.
  • onDisappear runs when SwiftUI frees the view struct from memory.
open as a page

In SwiftUI, what does an @main App type declare, and how does a WindowGroup turn its content into windows?

level: juniorimportance: must knowfreq 72%

basics

~20 s

A type conforming to App and marked @main is the app's single entry point, and its body returns scenes. A WindowGroup's content is a template: every window it creates gets its own view hierarchy and its own @State storage.

open as a page

How do you keep a SwiftUI view's previews fast and offline when the screen normally loads its feed from a network client?

level: middleimportance: must knowfreq 50%

basics

~20 s

A SwiftUI preview runs the view's real code, so a client built inside the view calls the network. Inject the client through init or the environment, give previews a mock with fixtures, and fence that code with #if DEBUG.

open as a page

In SwiftUI, why is the task modifier usually preferred over onAppear with a Task inside for loading a screen's data?

level: middleimportance: must knowfreq 80%

basics

~20 s

The task modifier starts async work before the view appears and SwiftUI cancels it after the view disappears; a Task created inside onAppear is unstructured, keeps running after the user leaves, and needs a stored handle to cancel.

open as a page

In SwiftUI, how does the scenePhase environment value differ when read in a view versus in the App, and where do you save edits?

level: middleimportance: must knowfreq 65%

basics

~20 s

Read in a view, scenePhase is the phase of the scene containing that view; read in the App, it aggregates every scene. Save a window's edits from its own view when that scene's phase changes; free app-wide resources in the App.

open as a page

In SwiftUI, how do you declare previews with the #Preview macro, and how do names and traits let one view show several states?

level: juniorimportance: should knowfreq 42%

basics

~20 s

#Preview is a freestanding macro that takes an optional name, optional traits and a closure returning the view to render. Write one named #Preview per state, and use traits such as sizeThatFitsLayout or landscapeLeft for layout and orientation.

open as a page

In a SwiftUI #Preview, how do you give a component that takes a Binding real, editable state, and what does @Previewable generate?

level: middleimportance: should knowfreq 40%

basics

~20 s

Tag a root-level @State in the #Preview body with @Previewable. The macro generates an embedded view, turns tagged declarations into its properties, and lets you pass $value as a live binding instead of a frozen .constant one.

open as a page

In SwiftUI, how does refreshable drive pull to refresh on a List, and why does wrapping its work in a Task break it?

level: middleimportance: should knowfreq 50%

basics

~20 s

refreshable(action:) stores a RefreshAction in the environment; a List on iOS offers pull to refresh and keeps its indicator visible while the async handler runs, so wrapping the work in Task { } returns at once and hides it early.

open as a page

In SwiftUI, how do WindowGroup, Window, Settings and DocumentGroup differ, and which of them can an iOS app declare?

level: middleimportance: should knowfreq 30%

basics

~20 s

WindowGroup opens identical, independent windows; Window is one unique window; Settings drives the Mac Settings menu item; DocumentGroup adds document browsing, opening and saving. Of the four, only WindowGroup and DocumentGroup are available on iOS.

open as a page

In SwiftUI, what do onChange(of:initial:_:)'s initial parameter and two-value closure give you, and when is onReceive the better fit?

level: seniorimportance: should knowfreq 45%

basics

~20 s

onChange(of:initial:_:), added in iOS 17, runs a synchronous action when an Equatable value changes, can pass both old and new values, and with initial: true also runs on first appearance; onReceive reacts to each event a Combine publisher emits.

open as a page

In a SwiftUI stock-quote screen, how do you reload when the selected symbol changes and stop polling when the screen disappears?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Attach task(id: symbol) with a polling loop: SwiftUI starts it before the screen appears, cancels and restarts it when symbol changes, and cancels it after the screen disappears, provided the loop's sleep and requests honour cancellation.

open as a page

In a SwiftUI app, how do you receive the push-notification device token through @UIApplicationDelegateAdaptor, and what should stay out of that delegate?

level: seniorimportance: should knowfreq 50%

basics

~10 s

Write an NSObject class conforming to UIApplicationDelegate that implements application(_:didRegisterForRemoteNotificationsWithDeviceToken:), and declare it once in the App with @UIApplicationDelegateAdaptor. SwiftUI creates it and forwards callbacks; foreground and background handling stays with scenePhase.

open as a page

As the iOS lead on a 40-screen SwiftUI app whose previews keep breaking or calling the network, what preview standard would you set for the team?

level: principalimportance: should knowfreq 25%

basics

~20 s

Treat previews as a reviewed fixture layer. Screens take their services through init or the environment, previews use shared offline mocks behind #if DEBUG, every screen previews an agreed set of states, and new code uses #Preview instead of PreviewProvider.

open as a page

When moving a large UIKit app to the SwiftUI App life cycle, how do you plan the app delegate, scene delegate and window changes?

level: principalimportance: should knowfreq 25%

basics

~20 s

Add an @main App struct, keep the old app delegate through @UIApplicationDelegateAdaptor, remove storyboard launch keys, move foreground and background handling to scenePhase, and host existing screens in a WindowGroup. Enable iPad multi-window only once per-window state is ready.

open as a page

In SwiftUI on iOS 18 and later, how does a PreviewModifier share one mocked environment across many previews, and when is it worth using?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

PreviewModifier, added in iOS 18, builds expensive mock state once in makeSharedContext(), which the preview system caches and reuses, then injects it in body(content:context:). Previews opt in with the .modifier trait, so setup lives in one place.

open as a page

A SwiftUI document editor calls openWindow(value: document.id) to open a document in its own iPad window, but nothing appears; what do you check?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

Check that windows are possible: supportsMultipleWindows is false on iPhone and on iPad without UIApplicationSupportsMultipleScenes, and SwiftUI then ignores openWindow. Then check that a WindowGroup(for:) declares the exact value type, and that no window already shows that value.

open as a page