Next.js Course
Next.js
/
Intermediate

Client-Side Fetching

Definition

Fetching data from the browser AFTER the initial page load, typically responding to user interactions like clicking a button or typing in a search bar.

Explain Like I'm New

Server fetching is for the initial page load. Client fetching is for everything that happens after. If a user types into a 'Search' bar, you can't reload the entire server page. You must fetch the search results from the client browser using React Query or SWR.

Real World Example

An infinite scrolling feed (like Twitter). The server provides the first 10 tweets. As the user scrolls down, the client browser fetches the next 10 tweets and appends them to the list.

Common Use Cases

  • •Infinite scrolling
  • •Search autocomplete
  • •Pagination without URL changes

Interactive Example

'use client'; // Must be a client component
import useSWR from 'swr';

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function LiveSearch() {
  const [query, setQuery] = useState('');
  
  // SWR handles the loading state, caching, and background refetching!
  const { data, error, isLoading } = useSWR(`/api/search?q=${query}`, fetcher);

  return (
    <div>
      <input onChange={(e) => setQuery(e.target.value)} />
      {isLoading && <p>Searching...</p>}
      {data && data.results.map(item => <p>{item.name}</p>)}
    </div>
  );
}

Interview Questions

basic

  • If you need to fetch data when a user clicks a 'Load More' button, should you use Server or Client fetching?

intermediate

  • Why does Next.js strongly recommend using libraries like SWR or React Query for client-side fetching instead of standard `useEffect`?

Flash Cards

Question

Load more?

Click to reveal answer
Answer

Client-side fetching. You are responding to a user event after the initial render.

Question

Why use libraries?

Click to reveal answer
Answer

Standard `fetch` inside `useEffect` is incredibly buggy. It doesn't handle caching, deduping, retries on failure, or race conditions. SWR and React Query solve all these complex problems out of the box.