SwiftUI Trick: Lazy View for Efficient Navigation
When using NavigationLink in SwiftUI, the destination view is initialized immediately, even if it's not navigated to. This can lead to performance issues, especially if the destination is resource-heavy.
The Problem
Even if the user never taps the link, DetailView() is created in memory.
The Solution: LazyView
To delay initialization until the navigation actually happens, wrap the destination in a LazyView:
Why This Works?
-
LazyViewdefers the creation ofDetailViewuntil the navigation occurs. -
Improves performance, especially in lists with many navigation links.
-
Prevents unnecessary view construction, saving memory.
💡 Use this trick in performance-sensitive apps!

Comments
Post a Comment