Blog>
Snippets

Parallel Queries with React Query

Showcase how to execute multiple queries in parallel with React Query to fetch independent data sources simultaneously for efficiency.
import { useQuery } from 'react-query';
import axios from 'axios';

// Fetch users
const fetchUsers = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/users');
  return data;
};

// Fetch posts
const fetchPosts = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
};
Define asynchronous functions to fetch users and posts from separate endpoints using axios.
function MyComponent() {
  // Execute parallel queries
  const { data: users, isLoading: isLoadingUsers } = useQuery('users', fetchUsers);
  const { data: posts, isLoading: isLoadingPosts } = useQuery('posts', fetchPosts);

  if (isLoadingUsers || isLoadingPosts) return <div>Loading...</div>;

  return (
    <div>
      <h1>Users</h1>
      {users.map(user => <p key={user.id}>{user.name}</p>)}
      <h1>Posts</h1>
      {posts.map(post => <p key={post.id}>{post.title}</p>)}
    </div>
  );
}
Use the useQuery hook to execute two queries in parallel. This component fetches both users and posts data simultaneously and displays them.