Blog>
Snippets

Using React Query for Data Fetching and Loading States

Integrate React Query for managing server state in Next.js 14 and implementing loading states with the use of 'isLoading' flag.
import { useQuery } from 'react-query';
import axios from 'axios';

// This is a custom hook that uses react-query's useQuery
// to fetch data from an API endpoint
const useFetchData = (url) => {
  // The useQuery hook is used to fetch data from the server.
  // It returns an object with properties including: status, data, error, and isLoading.
  return useQuery('data', async () => {
    const { data } = await axios.get(url);
    return data;
  });
};
This piece of code defines a custom hook 'useFetchData' using React Query's 'useQuery' to fetch data from a URL. The hook returns the query object including the 'isLoading' flag which indicates whether the query is in a loading state.
import React from 'react';
import { useFetchData } from './hooks/useFetchData';

// Example of a component that fetches data using the useFetchData
// hook and displays loading state or the fetched data.
const DataComponent = ({ url }) => {
  const { data, isLoading, error } = useFetchData(url);

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

  // Render the fetched data
  return (
    <div>
      <h1>Fetched Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export default DataComponent;
This piece of code represents a React component 'DataComponent' which uses the 'useFetchData' custom hook to fetch data from a URL. It uses the 'isLoading' flag to render a loading state, handles potential errors, and then renders the fetched data.
import { QueryClient, QueryClientProvider } from 'react-query';
import DataComponent from './DataComponent';

// Initialize a QueryClient instance,
// which will be used to provide react-query context for the entire app.
const queryClient = new QueryClient();

function MyApp() {
  return (
    <QueryClientProvider client={queryClient}>
      <DataComponent url='/api/data' />
    </QueryClientProvider>
  );
}

export default MyApp;
This is the main entry component 'MyApp' of the Next.js application, where QueryClientProvider from React Query is used to wrap the application's components. 'DataComponent' is provided as a child, which receives a URL to fetch data from the server. It ensures that React Query context is available in the component tree.