Skip to content

Instantly share code, notes, and snippets.

@satishVekariya
Last active February 7, 2026 16:01
Show Gist options
  • Select an option

  • Save satishVekariya/fea6cb5930639144128aefec9605a649 to your computer and use it in GitHub Desktop.

Select an option

Save satishVekariya/fea6cb5930639144128aefec9605a649 to your computer and use it in GitHub Desktop.
Lazy loads swiftui view in the List
/// ForEach that renders items in batches for smoother scrolling
public struct BatchedForEach<Data, ID, Content>: View
where Data: RandomAccessCollection,
Data.Index == Int,
ID: Hashable,
Content: View {
@State private var renderedCount: Int
private let data: Data
private let id: KeyPath<Data.Element, ID>
private let batchSize: Int
private let content: (Data.Element) -> Content
public init(
_ data: Data,
id: KeyPath<Data.Element, ID>,
batchSize: Int = 20,
@ViewBuilder content: @escaping (Data.Element) -> Content
) {
self.data = data
self.id = id
self.batchSize = batchSize
self.content = content
self._renderedCount = State(initialValue: min(batchSize, data.count))
}
public var body: some View {
ForEach(0..<renderedCount, id: \.self) { index in
content(data[index])
.onAppear {
loadMoreIfNeeded(currentIndex: index)
}
}
}
private func loadMoreIfNeeded(currentIndex: Int) {
// Load next batch when approaching the end
if currentIndex >= renderedCount - 5 && renderedCount < data.count {
renderedCount = min(renderedCount + batchSize, data.count)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment