Using TanStack Query for Scalable React Applications
With built-in caching, retries, and background refetching, TanStack Query takes the pain out of CRUD operations in large-scale React applications.
Join the DZone community and get the full member experience.
Join For FreeWhen building React applications, data fetching often starts with the native fetch API or tools like Axios. While this approach works for small projects, larger applications require features such as caching, retries, synchronization, and request cancellation, and it is here that TanStack Query, formerly React Query, excels. It provides a battle-tested abstraction for CRUD operations with powerful state management built in.
In this article, we’ll walk through fetching data with useQuery, performing mutations with useMutation, and highlighting some features that make TanStack Query a helpful tool for scaling React apps.
Fetching Data With useQuery (GET)
The useQuery hook is designed for GET API calls. Here’s an example:
const fetchMovies = async () => {
const response = await fetch('/v1/api/movies');
if (!response.ok) throw new Error('Failed to fetch movies');
return response.json();
};
export const useFetchMoviesList = () => {
return useQuery({
queryKey: ['movies_list'],
queryFn: fetchMovies,
retry: 3,
});
};
In this example, the fetchMovies function requests or fetches data from '/v1/api/movies' and throws an error if the response fails, and returns the JSON data when successful.
We wrap this in a custom hook, useFetchMoviesList, which uses useQuery. The queryKey identifies the request for caching, the queryFn defines how to fetch the data, and retry: three retries failed requests up to three times.
The useFetchMoviesList hook can be consumed in a MovieList component as follows:
const MoviesList = () => {
const { data, isLoading, isError } = useFetchMoviesList();
if (isLoading) return <span>Loading...</span>;
if (isError) return <span>Something went wrong</span>;
return (
<ul>
{data.map((movie: { id: number; title: string }) => (
<li key={movie.id}>{movie.title}</li>
))}
</ul>
);
};
Inside the MoviesList component, the hook provides built-in states, including isLoading, isError, and data. With these states, you no longer manage useState or useEffect manually because TanStack Query handles them for you. The component displays a loading message while the API call runs, an error message if the request fails after retries, and the list of movies once the data loads successfully.
Performing Mutations With useMutation
The useMutation hook is designed for POST/PUT/DELETE API calls.
const addMovie = async (movieId: string) => {
const response = await fetch('/v1/api/movies', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ id: movieId }),
});
if (!response.ok) throw new Error('Failed to add movie');
return response.json();
};
export const useAddMovie = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: addMovie,
onSuccess: () => {
// To GET the updated movie list since we added a movie
queryClient.invalidateQueries({ queryKey: ['movies_list'] });
},
});
};
In this example, the addMovie function sends a POST request to 'v1/api/movies' with the new movie’s ID in the request body. If the response fails, it throws an error; otherwise, it returns the parsed JSON response.
We then wrap it in a custom hook, useAddMovie, which uses useMutation. The mutationFn defines how the mutation is performed, and the onSuccess callback calls invalidateQueries to refresh the cached movies_list query. This ensures the UI reflects the updated list immediately after a movie is added.
The useAddMovie hook can be consumed in an AddMovieButton component as follows:
const AddMovieButton = () => {
const { mutate, isLoading, isError } = useAddMovie();
const handleAddMovie = () => {
mutate('123');
};
return (
<section>
<button onClick={handleAddMovie} disabled={isLoading}>
{isLoading? 'Adding...': 'Add Movie'}
</button>
{isError && <span>Failed to add movie</span>}
</section>
);
};
The AddMovieButton component utilizes the useAddMovie hook to manage the addition of a new movie. Inside the element, it extracts mutate, isLoading, and isError from the hook.
The handleAddMovie function calls mutate('123'), which triggers the mutation to add a movie with the ID '123'. While the request is in progress, the button becomes disabled and shows 'Adding...'. If the request fails, the component displays an error message. Otherwise, once successful, TanStack Query automatically refreshes the movie list.
In short, this component provides a clean way to add a movie, showing the user real-time feedback for loading and error states without requiring extra state management code.
Note: To use useQuery and useMutation, your component tree must be wrapped in a QueryClientProvider. This sets up the client context for TanStack Query.
TanStack Query eliminates boilerplate code and provides built-in retries, refetching, error handling, and caching, making developers feel more efficient and productive. It also has the following features that can be helpful in managing server state effectively:
- Retry logic: Configure retry (e.g., retry: 3) so that transient failures don't break user flow.
- Conditional fetching: Set enabled to false so the query waits until you satisfy the required conditions.
- Caching: TanStack Query caches data after the first fetch and shares it across components, reducing duplicate requests.
- Request cancellation: Abort queries if they are no longer needed, for example, when a component unmounts or the user navigates away.
- Background refetching: TanStack Query automatically keeps data fresh when the user refocuses the browser or reconnects to the network.
TanStack Query can be useful in large-scale applications as it eliminates repetitive boilerplate, reduces the risk of inconsistencies, and delivers production-grade features, such as caching and synchronization, out of the box. For smaller applications that make only a few API requests, however, plain fetch may be sufficient. In those cases, introducing TanStack Query could add unnecessary bundle size without providing significant benefits.
Conclusion
TanStack Query has become a good tool for developers tackling complex applications by providing declarative data fetching, caching, retries, and mutations. For large-scale React apps, adopting this tool can be helpful for building reliable and maintainable systems.
Opinions expressed by DZone contributors are their own.
Comments