How does SwiftUI manage state?

Viewed 110

I have a UIViewControllerRepresentable implementation and I've noticed that makeUIViewController is only called once whereas init is called multiple times.

Similarly, the view controller's init is called multiple times but the scroll view that it wraps is only created once and viewDidLoad is only called once.

Does SwiftUI hold references to controls and then plug them back into new view controller instances? Is there description somewhere of the life cycle?

1 Answers

It's probably only calling makeUIViewController if the new view is different from the old view (according to your implementation of Equatable).

I think SwiftUI is re-creating the struct-based view hierarchy quite often (on state changes) to check if anything changed. Every time this happens, your init method is called. But if nothing has changed, SwiftUI won't request a new instance of the ViewController.

Related