Blog>
Snippets

Implementing Parallel Queries with React Query

Provide an example of executing parallel queries using React Query in a server-side rendering scenario, highlighting the performance benefits.
import { useQueries } from 'react-query';
import axios from 'axios';
Imports the useQueries hook from React Query and axios for making HTTP requests.
const fetchData = async (url) => {
  const { data } = await axios.get(url);
  return data;
};
Defines an asynchronous function, fetchData, which takes a URL and returns the fetched data using axios.
const useFetchParallelQueries = () => {
  return useQueries([
    { queryKey: ['post', 1], queryFn: () => fetchData('https://jsonplaceholder.typicode.com/posts/1') },
    { queryKey: ['post', 2], queryFn: () => fetchData('https://jsonplaceholder.typicode.com/posts/2') }
  ]);
};
Implements the useFetchParallelQueries hook to execute parallel queries using useQueries. It fetches data from two endpoints concurrently.
const BlogPosts = () => {
  const results = useFetchParallelQueries();

  if (results.some(result => result.isLoading)) return <div>Loading...</div>;

  if (results.some(result => result.error)) return <div>Error loading data</div>;

  return (
    <div>
      {results.map((result, index) => (
        <div key={index}>Post Title: {result.data.title}</div>
      ))}
    </div>
  );
};
Defines a functional component, BlogPosts, which uses the useFetchParallelQueries hook. It renders loading state, error states and the list of fetched blog post titles.