Blog>
Snippets

Adding React Query for Data Fetching

Demonstrate the setup of React Query in Next.js for managing server state, including use of useQuery hook to fetch and cache data from an API.
import { QueryClient, QueryClientProvider } from 'react-query';

const queryClient = new QueryClient();

function MyApp({ Component, pageProps }) {
  return (
    <QueryClientProvider client={queryClient}>
      <Component {...pageProps} />
    </QueryClientProvider>
  );
}

export default MyApp;
This code sets up the QueryClientProvider at the root of your Next.js application, which enables all child components to use React Query hooks.
import { useQuery } from 'react-query';

async function fetchUserData(userId) {
  const response = await fetch(`/api/user/${userId}`);
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
}

function UserProfile({ userId }) {
  const { data, isLoading, error } = useQuery(['user', userId], () => fetchUserData(userId));

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

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.email}</p>
    </div>
  );
}

export default UserProfile;
This code demonstrates the use of the useQuery hook to fetch and cache user data from an API and consume it within a component. It defines a fetch function, fetchUserData, and the useQuery call triggers this function.