How to use React Query for data fetching
· Category: React
How to use React Query for data fetching
Introduction
React Query (TanStack Query) is a data-fetching library that handles caching, background updates, deduplication, and error retries automatically. It removes the need for boilerplate state management around server data.
Basic Usage
Wrap your app with QueryClientProvider, then use the useQuery hook:
import { useQuery } from "@tanstack/react-query";
function Posts() {
const { data, isLoading, error } = useQuery({
queryKey: ["posts"],
queryFn: async () => {
const res = await fetch("/api/posts");
return res.json();
},
});
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <ul>{data.map(post => <li key={post.id}>{post.title}</li>)}</ul>;
}
Mutations and Cache Invalidation
Use useMutation for write operations and invalidate related queries to keep the UI in sync:
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: createPost,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["posts"] });
},
});
React Query pairs well with modern API patterns. Understanding what is REST API helps design endpoints that work naturally with query keys. For backend considerations, how-to-design-restful-api covers conventions that simplify client logic.