javascript / expert
Snippet
Async Generator Windowing for Paginated React Collection Iteration
Handling massive server arrays in React state often causes memory pressure if all pages are fetched simultaneously. Async generators yield paginated array chunks on demand, enabling controlled chunking through 'for await...of' loops without blocking the main event loop during rendering batches.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
export async function* fetchPaginatedBatchStream(fetcher, batchSize = 50) {let page = 0;let hasMore = true;while (hasMore) {const chunk = await fetcher(page, batchSize);if (!Array.isArray(chunk) || chunk.length === 0) {hasMore = false;break;}yield chunk;if (chunk.length < batchSize) hasMore = false;page++;}}
react
Breakdown
1
export async function* fetchPaginatedBatchStream(fetcher, batchSize = 50)
Defines an async generator function returning an AsyncIterator of array batches.
2
yield chunk;
Yields the current fetched batch array to the consumer while pausing internal generator execution state.
3
if (chunk.length < batchSize) hasMore = false;
Evaluates stream termination criteria based on returned collection size to break the loop control flow.