In SwiftUI, it is recommended not to store ViewBuilder closures in sub-views but instead evaluate them directly in init and store the result (example: https://www.youtube.com/watch?v=yXAQTIKR8fk). That has the advantage, as I understand it, that the closure doesn't need to be re-evaluated on every layout pass.
On the other side, identity is a very important topic in SwiftUI to get the UI working properly.
Now I have this generic view I'm using with a closure which is displayed in two places (HStack & VStack). Should I store the closure result and get the performance improvements, or evaluate it in place and get correct identities (if that is even an issue)?
Simplified example:
struct DynamicStack<Content: View>: View {
@ViewBuilder var content: () -> Content
var body: some View {
ViewThatFits(in: .horizontal) {
HStack {
content()
}
VStack {
content()
}
}
}
}
vs
struct DynamicStack<Content: View>: View {
@ViewBuilder var content: Content
var body: some View {
ViewThatFits(in: .horizontal) {
HStack {
content
}
VStack {
content
}
}
}
}