ReactData FetchingGuide2026 Updated

React Fetch Data on Page Load— Complete Guide [2026]

useEffect · custom hook · SWR · TanStack Query · Next.js Server Component

January 20267 min readReact 18 · Next.js · SWR

Which Pattern Should You Use?

PatternBest forComplexity
useEffect + fetchLearning, simple one-off fetchesLow
Custom useFetchReusable across components, no dependencyLow
SWRMost production React appsLow
TanStack QueryComplex apps — pagination, mutations, cacheMedium
Server ComponentNext.js App Router — best performanceLow (Next.js only)
1

useEffect With fetch — Standard Pattern

The foundation — understand this first
3 min
components/UserList.jsx
import { useState, useEffect } from 'react'

export default function UserList() {
  const [users,   setUsers]   = useState([])
  const [loading, setLoading] = useState(true)
  const [error,   setError]   = useState(null)

  useEffect(() => {
    const controller = new AbortController()

    async function fetchUsers() {
      try {
        const res = await fetch('/api/users', { signal: controller.signal })
        if (!res.ok) throw new Error('Failed: ' + res.status)
        const data = await res.json()
        setUsers(data)
      } catch (err) {
        if (err.name !== 'AbortError') setError(err.message)
      } finally {
        setLoading(false)
      }
    }

    fetchUsers()
    return () => controller.abort()   // cleanup on unmount
  }, [])  // [] = run once on mount

  if (loading) return <p>Loading...</p>
  if (error)   return <p>Error: {error}</p>
  if (!users.length) return <p>No users found.</p>

  return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>
}
2

Reusable useFetch Custom Hook

DRY — one hook for all fetch calls
3 min
hooks/useFetch.js
import { useState, useEffect } from 'react'

export function useFetch(url) {
  const [data,    setData]    = useState(null)
  const [loading, setLoading] = useState(true)
  const [error,   setError]   = useState(null)

  useEffect(() => {
    if (!url) return
    const controller = new AbortController()
    setLoading(true)

    fetch(url, { signal: controller.signal })
      .then(res => { if (!res.ok) throw new Error('Failed: ' + res.status); return res.json() })
      .then(data => { setData(data); setLoading(false) })
      .catch(err => { if (err.name !== 'AbortError') { setError(err.message); setLoading(false) } })

    return () => controller.abort()
  }, [url])

  return { data, loading, error }
}

// Usage — one line anywhere
function ProductPage({ id }) {
  const { data: product, loading, error } = useFetch(`/api/products/${id}`)
  if (loading) return <Skeleton />
  if (error)   return <ErrorMessage message={error} />
  return <ProductDetail product={product} />
}
3

SWR — Recommended for Most Apps

Caching, revalidation, deduplication built-in
3 min
terminal
npm install swr
components/UserProfile.jsx
import useSWR from 'swr'

const fetcher = url => fetch(url).then(r => r.json())

export default function UserProfile({ userId }) {
  const { data, error, isLoading } = useSWR(
    `/api/users/${userId}`,
    fetcher
  )

  if (isLoading) return <Skeleton />
  if (error)     return <ErrorMessage />
  return <div>{data.name}</div>
}

// SWR gives you for free:
// ✅ Request deduplication
// ✅ Cache — instant display on revisit
// ✅ Background revalidation
// ✅ Focus revalidation (reloads when tab regains focus)
// ✅ Automatic retry on error
// ✅ Loading and error states
4

TanStack Query — Complex Apps

Full-featured — pagination, mutations, cache control
3 min
terminal
npm install @tanstack/react-query
app.jsx + components/Posts.jsx
// Setup — wrap app in QueryClientProvider
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
const queryClient = new QueryClient()

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Posts />
    </QueryClientProvider>
  )
}

// Usage in component
import { useQuery } from '@tanstack/react-query'

function Posts() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['posts'],
    queryFn: () => fetch('/api/posts').then(r => r.json()),
    staleTime: 5 * 60 * 1000,   // data fresh for 5 minutes
  })

  if (isLoading) return <Skeleton />
  return <ul>{data.map(p => <li key={p.id}>{p.title}</li>)}</ul>
}
5

Next.js Server Component — Best Performance

App Router — no useEffect needed
2 min
app/users/page.jsx
// ✅ Server Component — async/await directly in component
// No useEffect, no useState, no loading state needed
// Page only renders when data is ready

export default async function UsersPage() {
  const res   = await fetch('https://api.example.com/users', {
    next: { revalidate: 60 }   // ISR — revalidate every 60 seconds
  })
  const users = await res.json()

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  )
}

// For dynamic data (per-request, no cache):
// fetch(url, { cache: 'no-store' })

Server Components are the best way to fetch data in Next.js App Router. No waterfall, no client bundle overhead, data is ready before the page HTML is sent to the browser.

Handle Loading, Error, and Empty States

components/DataList.jsx
export default function DataList({ data, loading, error }) {
  if (loading) return (
    <div className="space-y-3">
      {[...Array(3)].map((_, i) => (
        <div key={i} className="h-12 bg-gray-100 animate-pulse rounded-lg" />
      ))}
    </div>
  )

  if (error) return (
    <div className="rounded-lg bg-red-50 border border-red-200 p-4">
      <p className="text-red-700 text-sm">Failed to load: {error}</p>
    </div>
  )

  if (!data?.length) return (
    <p className="text-gray-500 text-center py-8">No items found.</p>
  )

  return <ul>{data.map(item => <li key={item.id}>{item.name}</li>)}</ul>
}

Frequently Asked Questions

How do I fetch data when a React component loads?+
Use useEffect with empty deps: useEffect(() => { fetch('/api/data').then(r => r.json()).then(setData) }, []). The empty [] means it runs once on mount. Always use AbortController to cancel if the component unmounts before the fetch completes.
React fetch runs twice in development — how to stop it?+
React 18 StrictMode mounts components twice in development. Fix with AbortController: const controller = new AbortController(); fetch(url, { signal: controller.signal }); return () => controller.abort(). The first fetch is cancelled, only the second completes.
Should I use useEffect for data fetching?+
For simple cases yes, but SWR or TanStack Query are better for production — they handle caching, deduplication, retries, and background revalidation automatically. useEffect requires you to implement all of that yourself.
How do I re-fetch data when props change?+
Add the prop to useEffect's dependency array: useEffect(() => { fetchUser(userId) }, [userId]). With SWR: useSWR(`/api/users/${userId}`, fetcher) — it automatically re-fetches when the URL changes.
How do I handle errors when fetching?+
Use try/catch with async/await: try { const res = await fetch(url); if (!res.ok) throw new Error('Failed: ' + res.status); setData(await res.json()) } catch (err) { if (err.name !== 'AbortError') setError(err.message) }
Best way to fetch data in Next.js App Router?+
Use async Server Components — they can directly await fetch() without useEffect. No loading state needed — the page only renders when data is ready. For client-side fetching after navigation, use SWR or TanStack Query.

Need Expert Help?

We Build Production-Grade React Apps

Softplix builds full-stack React and Next.js applications. Need help with data fetching architecture or API integration? We can help.

Talk to an Engineer