Skip to main content
08

Infinite scroll

MediumreactIntersectionObserverdata fetchinguseEffect

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Build an infinitely scrolling feed. api.js is a fake server with 95 posts, served 10 at a time with a delay, and Post.js renders one post. Right now the feed is empty.

js
const { items, nextCursor } = await fetchPosts({ cursor: 0, limit: 10 })
// nextCursor is the cursor of the next page, or null after the last post

Requirements

  • Load the first page when the feed appears.
  • When the user scrolls near the bottom, load the next page and append it. Use IntersectionObserver, not a scroll event listener.
  • Never request the same page twice, and never send a new request while one is still loading.
  • While a page is loading, show Loading more posts....
  • Errors: the API fails the first time page 3 is requested. Show an error message with a Retry button, and don't retry automatically. Retrying loads the page and scrolling continues normally.
  • After the last post, show You've reached the end. and stop requesting.

Accessibility

  • The loading, error and end messages are in a role="status" region, so screen readers announce them.

Note

The preview updates as you type. There are no automated tests for this challenge yet: scroll to the end, check the error and the retry, and watch the console for duplicate requests. Then compare with the reference solution.

index.js renders the app in <StrictMode>, which runs effects twice in development. Your feed must still load page 1 only once.

Follow-ups interviewers ask

  • The feed now has 10,000 posts. What happens to the DOM, and how does virtualization fix it?
  • Restore the scroll position when the user navigates to a post and comes back.
  • Turn the logic into a reusable useInfiniteScroll hook.
  • Should you use AbortController here? What would it cancel?

The approach

The state describes where the feed is:

  • posts: everything loaded so far.
  • cursor: the next page to ask for, or null when there is nothing left.
  • status: idle, loading or error.

An invisible sentinel <div> sits after the last post. An IntersectionObserver watches it, and when it comes within 200px of the viewport, loadMore() runs. There is no separate "load the first page on mount" code: with no posts, the sentinel is already on screen, so the observer triggers the first load too.

Loading diagram...

No duplicate requests

The guard is a ref, loadingRef, not the status state. State updates only show up on the next render, so two calls in the same tick (the observer firing twice, or StrictMode running the effect twice) would both read status === 'idle' and both fetch. A ref changes immediately, so the second call returns early.

Why the observer is recreated

loadMore reads cursor, so it changes after every page, and the effect re-runs with the new loadMore. Re-observing has a useful side effect: an IntersectionObserver reports the current state as soon as it starts observing. If the new page is too short to push the sentinel off screen, the observer fires again and loads another page, until the screen is filled.

Errors and the end

  • On error, the effect doesn't create an observer. The feed waits for the user to press Retry instead of retrying in a loop against a failing server.
  • When cursor is null, the observer isn't created either, so no more requests are sent.

Why not a scroll listener

A scroll handler runs on the main thread dozens of times per second and has to measure layout (scrollHeight, getBoundingClientRect) each time, which forces reflow. IntersectionObserver is computed by the browser off the critical path and only calls you when visibility actually changes.

What interviewers look for

  • IntersectionObserver with a sentinel and a rootMargin.
  • A synchronous in-flight guard, and being able to explain why state alone isn't enough.
  • Loading, error with manual retry, and end-of-list states.
  • Cleaning up the observer.
  • Knowing when to reach for virtualization.

Reference solution

src/App.js

jsx
import { useCallback, useEffect, useRef, useState } from 'react'

import { fetchPosts } from './api'
import Post from './Post'

const PAGE_SIZE = 10

export default function App() {
  const [posts, setPosts] = useState([])
  // The cursor of the next page to load; null once the last page has loaded.
  const [cursor, setCursor] = useState(0)
  const [status, setStatus] = useState('idle') // 'idle' | 'loading' | 'error'
  const loadingRef = useRef(false)
  const sentinelRef = useRef(null)

  const loadMore = useCallback(async () => {
    // A ref, not state: two calls in the same tick both see it immediately.
    if (loadingRef.current || cursor === null) return
    loadingRef.current = true
    setStatus('loading')
    try {
      const page = await fetchPosts({ cursor, limit: PAGE_SIZE })
      setPosts((current) => [...current, ...page.items])
      setCursor(page.nextCursor)
      setStatus('idle')
    } catch {
      setStatus('error')
    } finally {
      loadingRef.current = false
    }
  }, [cursor])

  useEffect(() => {
    const sentinel = sentinelRef.current
    // After an error, wait for Retry instead of hammering the server.
    if (!sentinel || status === 'error' || cursor === null) return
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) loadMore()
      },
      // Start loading a little before the user actually reaches the bottom.
      { rootMargin: '200px' },
    )
    observer.observe(sentinel)
    return () => observer.disconnect()
  }, [loadMore, status, cursor])

  return (
    <main className="feed">
      <h1>Feed</h1>
      {posts.map((post) => (
        <Post key={post.id} post={post} />
      ))}

      <div ref={sentinelRef} aria-hidden="true" />
      <div className="status" role="status">
        {status === 'loading' && 'Loading more posts...'}
        {status === 'error' && (
          <>
            Couldn't load more posts.
            <button type="button" onClick={loadMore}>
              Retry
            </button>
          </>
        )}
        {cursor === null && "You've reached the end."}
      </div>
    </main>
  )
}