Exploring SwiftUI's LazyHStack and LazyVStack Views

Lazy Stacks allow for more optimization and a better user experience as the elements will load faster, only when visible. For elements that can be offscreen, you should use LazyVStack or LazyHStack instead of HStack and VStack.


In this tutorial, you will learn better scroll performance by using LazyHStack and LazyVStack instead of HStack and VStack.
With iOS 14, Apple gives you the ability to use lazy stacks in SwiftUI. While HStack and VStack load the content right away, LazyHStack and LazyVStack load the content as you scroll.

LazyVStack 
  • To test performance, we're creating 10,000 rows stacked vertically using a LazyVStack that is embedded inside a ScrollView. 
  • You'll notice a drastically better performance during scrolling and on initial load versus using VStack.
ScrollView {
	LazyVStack(spacing: 16) {
		ForEach(0 ..< 10000) { item in
			RoundedRectangle(cornerRadius: 20)
				.fill(Color.white)
				.frame(height: 100)
				.shadow(radius: 100)
		}
	}
	.padding()
}
..
LazyVGrid 
  • Just like LazyVStack, you can use LazyVGrid to load your items only when in view.
ScrollView {
    LazyVGrid(columns: [GridItem(.adaptive(minimum: 100))]) {
        ForEach(0 ..< 10000) { item in
            RoundedRectangle(cornerRadius: 20)
                .fill(Color.white)
                .frame(height: 100)
                .shadow(radius: 100)
        }
    }
    .padding()
}
..

Comments