How does onChange work? (Chapter 6. Using Timeline View)

During the learning chapter 6, I couldn’t understand how the onChange works in CountdownView.

var body: some View {
Text(“(timeRemaining)”) // 5
.font(.system(size: size, design: .rounded))
.padding()
.onChange(of: date) { _ in // 6
timeRemaining -= 1
}
}
}

I believe that onChange triggers when the value changes. But I can’t understand why the modifier is called whenever the timeline view creates a new count view although the date is let which is immutable.

1 Like

Hi junhan! It seems passing in the argument counts as changing the value of date. Here’s a simpler example, where tapping the button updates the State property id so the view updates, passing the current date to ChangeView :

struct ContentView: View {
  @State var id = UUID()
  var body: some View {
    VStack {
      ChangeView(date: Date())
      Button("Update date view") {
        id = UUID()
      }
      .id(id)
    }
  }
}

struct ChangeView: View {
  let date: Date
  var body: some View {
    Text("Date changed to \(date)")
      .onChange(of: date) { _ in
        print(date)
      }
  }
}

Modified from an example in Mastering SwiftUI’s onChange | fatbobman | Medium

2 Likes

Thank for your reply. Now I’ve got it!