68Build infinite scrolling using IntersectionObserver
mediumAbout 35 minutesCodingreactintersection-observerpagination
Problem
Build <InfiniteList fetchPage={fetchPage} />. fetchPage(page) (pages start at 1) resolves to { items: string[], hasMore: boolean }.
- Load page 1 on mount.
- Render the items as
<li>elements, followed by an empty sentinel<div data-testid="sentinel" />while there are more pages. - When the sentinel scrolls into view (use
IntersectionObserverwithrootMargin: "200px"), load the next page and append its items. - Show
<p role="status">Loading…</p>while a page loads, and<p>You have seen everything</p>whenhasMoreis false. - On failure, show
<p role="alert">with a Retry button that loads the same page again.
Requirements
- Never load the same page twice, even if the observer fires several times while a page is loading.
- Stop observing once there are no more pages.
- Disconnect the observer on unmount.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Video walkthroughs
Stuck? Watch someone solve it, then try again on your own.
Step-by-step
You need items, page (the last loaded page), hasMore, status ("idle", "loading" or "error").
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 4 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.