onAppear vs .task — when to use which?
The gist
.onAppear { }— a synchronous callback: the view entered the hierarchy. Paired with.onDisappear. It cancels nothing and knows nothing about async..task { }— starts aTasktied to the view's lifetime: the closure isasync, and when the view disappears (or theidchanges) the task is cancelled automatically. This is the standard way to load data with async/await..task(id:) { }— restarts whenidchanges: the previous task is cancelled and a new one starts. Ideal for "reload when the query / selected item changes".
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep