How to fetch paginated API data in React

Fetching paginated data from APIs is essential for handling large datasets efficiently without overwhelming the client or server. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented pagination in countless data-driven applications over my 11 years of React development. The most effective approach is using state to track the current page and useEffect to fetch data whenever the page changes. This method provides smooth pagination with proper loading states and error handling.

Use useState to track the page number and useEffect to fetch data when it changes.

import { useState, useEffect } from 'react'

const PaginatedData = () => {
  const [data, setData] = useState([])
  const [page, setPage] = useState(1)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true)
      try {
        const response = await fetch(`/api/items?page=${page}&limit=10`)
        const result = await response.json()
        setData(result.items)
      } catch (error) {
        console.error('Error:', error)
      } finally {
        setLoading(false)
      }
    }
    fetchData()
  }, [page])

  return (
    <div>
      {loading ? <p>Loading...</p> : data.map(item => <div key={item.id}>{item.name}</div>)}
      <button onClick={() => setPage(p => p - 1)} disabled={page === 1}>Previous</button>
      <button onClick={() => setPage(p => p + 1)}>Next</button>
    </div>
  )
}

Here the page state tracks the current page number. The useEffect hook triggers a fetch request whenever page changes, passing the page number as a query parameter. Loading state provides user feedback during data fetching. The Previous button is disabled on the first page to prevent invalid requests.

Best Practice Note:

This is the same pattern we use in CoreUI data tables for paginated API integration. Consider adding total page count from the API response to disable the Next button on the last page, and implement debouncing if users can rapidly click pagination controls.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author