Fetching Data with useQuery

Showcase how to use the useQuery hook to fetch data from an API, including handling loading, error states, and displaying the fetched data.
import { useQuery } from 'react-query';
import axios from 'axios';
First, import the necessary modules: useQuery from react-query for the data fetching, and axios for making the HTTP request.
const fetchPosts = async () => {
  const { data } = await axios.get('');
  return data;
Define an asynchronous function fetchPosts to retrieve posts from the JSONPlaceholder API using axios. The function returns the fetched posts.
const Posts = () => {
  const { isLoading, error, data } = useQuery('posts', fetchPosts);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>An error has occurred: {error.message}</div>;

  return (
      { => (
        <li key={}>{post.title}</li>
Use the useQuery hook within a functional component to fetch posts. The hook is provided with a unique key 'posts' and the fetchPosts function. Depending on the hook's state, display loading message, error message, or a list of fetched posts.