React

Simplify Your API Calls with TanStack Query

Dec 2024·4 min read·Mohammed Khan
Simplify Your API Calls with TanStack Query

Managing data fetching with useState and useEffect leads to boilerplate code. TanStack Query handles caching, loading states, error handling, retries, and query invalidation automatically.

Traditional State and Effect Approach

const [userData, setUserData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);

const fetchData = async () => {
  setIsLoading(true);
  try {
    const { data } = await getUserRequests();
    setUserData(data);
  } catch (err) {
    setError(err.message);
  }
  setIsLoading(false);
};

useEffect(() => {
  fetchData();
}, []);

TanStack Query Approach

Custom hooks with TanStack Query:

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";

export const useUserData = () => {
  return useQuery({
    queryKey: ["USERDATA"],
    queryFn: () => getUserRequests(),
  });
};

export const useUpdateUserName = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: updateUserName,
    onSuccess: () => queryClient.invalidateQueries(["USERDATA"]),
  });
};

Component Implementation

const { data: userData, isLoading, error } = useUserData();
const { mutate: updateUserName, isLoading: isUpdating } = useUpdateUserName();

Key Advantages

  1. Caching: Queries cached by default; subsequent requests fetch from cache
  2. Auto Refetch: Stale queries automatically refetch on component mount
  3. Retries: Failed requests retry automatically with configurable policy
  4. Error Handling: Centralized error management reduces boilerplate
  5. Query Invalidation: Invalidate and refetch queries with a single call
  6. Lifecycle Callbacks: On-success and on-error callbacks for custom actions

Related Articles

Next articleHow to Use Web Workers to Filter Large Datasets Without Freezing Your UI