React Query is a library that provides powerful data synchronization for React applications.
It offers caching, background updates, error handling, and optimistic updates out of the box.
React Query simplifies data fetching by providing a declarative API that handles caching, background updates, and error states automatically.
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
function UserProfile({ userId }) { const { data: user, isLoading, error } = useQuery({ queryKey: ['user', userId], queryFn: () => fetchUser(userId), });
const queryClient = useQueryClient(); const updateUser = useMutation({ mutationFn: updateUser, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['user', userId] }); }, });
if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>;
return ( <div> <h1>{user.name}</h1> <button onClick={() => updateUser.mutate({ id: userId, name: 'New Name' })}> Update Name </button> </div> ); }