Introducao ao SWR - Data Fetching no React

Iniciante | 35 min leitura | 2025.12.14

O que voce vai aprender neste tutorial

✓ Fundamentos do SWR
✓ Data Fetching
✓ Mutacao
✓ Controle de cache
✓ Revalidacao

Step 1: Configuracao

npm install swr

Step 2: Uso Basico

import useSWR from 'swr';

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

function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <div>Hello, {data.name}</div>;
}

Step 3: Configuracao Global

// app/providers.tsx
import { SWRConfig } from 'swr';

const fetcher = async (url: string) => {
  const res = await fetch(url);
  if (!res.ok) throw new Error('Failed to fetch');
  return res.json();
};

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <SWRConfig
      value={{
        fetcher,
        revalidateOnFocus: true,
        revalidateOnReconnect: true,
        dedupingInterval: 2000,
      }}
    >
      {children}
    </SWRConfig>
  );
}

Step 4: Fetch Condicional

function UserPosts({ userId }: { userId: string | null }) {
  // Se userId for null, nao faz o fetch
  const { data } = useSWR(
    userId ? `/api/users/${userId}/posts` : null
  );

  return <div>{/* ... */}</div>;
}

Step 5: Mutacao

import useSWR, { useSWRConfig } from 'swr';

function UpdateProfile() {
  const { mutate } = useSWRConfig();

  const updateUser = async (newData: any) => {
    await fetch('/api/user', {
      method: 'PUT',
      body: JSON.stringify(newData),
    });

    // Revalidar cache
    mutate('/api/user');
  };

  return <button onClick={() => updateUser({ name: 'New Name' })}>Update</button>;
}

Step 6: Atualizacao Otimista

function TodoList() {
  const { data, mutate } = useSWR('/api/todos');

  const addTodo = async (text: string) => {
    const newTodo = { id: Date.now(), text, completed: false };

    // Atualizar otimisticamente
    mutate([...data, newTodo], false);

    // Chamada de API
    await fetch('/api/todos', {
      method: 'POST',
      body: JSON.stringify({ text }),
    });

    // Revalidar
    mutate();
  };

  return (/* ... */);
}

Step 7: Paginacao

import useSWRInfinite from 'swr/infinite';

function InfiniteList() {
  const getKey = (pageIndex: number, previousPageData: any) => {
    if (previousPageData && !previousPageData.length) return null;
    return `/api/posts?page=${pageIndex}`;
  };

  const { data, size, setSize, isLoading } = useSWRInfinite(getKey);

  const posts = data ? data.flat() : [];
  const isLoadingMore = isLoading || (size > 0 && data && typeof data[size - 1] === 'undefined');

  return (
    <div>
      {posts.map((post) => (
        <div key={post.id}>{post.title}</div>
      ))}
      <button
        onClick={() => setSize(size + 1)}
        disabled={isLoadingMore}
      >
        {isLoadingMore ? 'Loading...' : 'Load More'}
      </button>
    </div>
  );
}

Step 8: Prefetch

import { preload } from 'swr';

// Prefetch no mouse hover
function UserCard({ userId }: { userId: string }) {
  const handleMouseEnter = () => {
    preload(`/api/users/${userId}`, fetcher);
  };

  return (
    <a href={`/users/${userId}`} onMouseEnter={handleMouseEnter}>
      View Profile
    </a>
  );
}

Resumo

SWR e uma biblioteca leve de data fetching desenvolvida pela Vercel. Ela automatiza cache e revalidacao usando a estrategia stale-while-revalidate.

← Voltar para a lista