← Trilha· Lição 6 de 8
React Query: fetching e cache
Buscar dados remotos com cache e estados de loading.
TanStack Query (React Query) gerencia fetching, cache e revalidação fora do componente.
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
const client = new QueryClient();
function Lista() {
const { data, isPending, error } = useQuery({
queryKey: ['posts'],
queryFn: async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5');
if (!res.ok) throw new Error('Falha');
return res.json();
},
});
if (isPending) return <p>Carregando…</p>;
if (error) return <p>Erro</p>;
return <ul>{data.map((p) => <li key={p.id}>{p.title}</li>)}</ul>;
}
function App() {
return (
<QueryClientProvider client={client}>
<Lista />
</QueryClientProvider>
);
}