Next.js Data

Client-Side Fetching

SWR, React Query, useEffect fetching, and real-time data patterns.

Advertisement

Client-Side Fetching

SWR, React Query, useEffect fetching, and real-time data patterns.

Overview

Client-side fetching handles dynamic, user-specific data.

Key Concepts

  • SWR — Stale-while-revalidate strategy
  • React Query — Powerful data fetching and caching
  • useEffect Fetching — Basic client-side fetching
  • Real-Time Data — WebSockets and polling
  • Optimistic Updates — Update UI before server response

Code Examples

// SWR example
'use client';
import useSWR from 'swr';

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

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

  if (isLoading) return <Spinner />;
  if (error) return <div>Error loading user</div>;

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.email}</p>
    </div>
  );
}

// React Query
'use client';
import { useQuery } from '@tanstack/react-query';

function TodoList() {
  const { data: todos, isLoading, error } = useQuery({
    queryKey: ['todos'],
    queryFn: () => fetch('/api/todos').then(res => res.json()),
    staleTime: 5 * 60 * 1000
  });

  if (isLoading) return <Spinner />;
  if (error) return <ErrorMessage error={error} />;

  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  );
}

// Polling for real-time updates
function LiveNotifications() {
  const { data } = useSWR('/api/notifications', fetcher, {
    refreshInterval: 30000 // Poll every 30 seconds
  });

  return (
    <div>
      {data?.map(notification => (
        <div key={notification.id}>{notification.message}</div>
      ))}
    </div>
  );
}

Practice

Build a real-time dashboard with SWR polling and optimistic updates.