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

NavigationLink("Go to Detail") { DetailView() // This gets initialized immediately! }

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:

struct LazyView<Content: View>: View { let build: () -> Content init(_ build: @escaping () -> Content) { self.build = build } var body: Content { build() } } NavigationLink("Go to Detail") { LazyView { DetailView() } // Now, it initializes only when needed! }

Why This Works?

  • LazyView defers the creation of DetailView until 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

Popular posts from this blog

āĻ•āĻŦāĻŋāĻ¤āĻž

Folder vs Group in Xcode 16