Blog>
Snippets

Custom Hooks for Data Fetching with React Query

Create a custom hook using React Query for fetching data, encapsulating query logic and enabling reusability across components.
import { useQuery } from 'react-query';

const fetchUserData = async (userId) => {
  const response = await fetch(`https://api.example.com/users/${userId}`);
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};

export const useFetchUserData = (userId) => {
  return useQuery(['user', userId], () => fetchUserData(userId), {
    // You can add React Query options here for caching, retries, etc.
    staleTime: 1000 * 60 * 5, // 5 minutes
  });
};
This custom hook (`useFetchUserData`) utilizes React Query's `useQuery` hook for fetching user data from an API. It encapsulates the data fetching logic making it reusable across components. The hook takes a `userId` as a parameter and returns the user data, together with React Query's loading, error, and other statuses. `staleTime` option is used here to specify how long the data remains fresh.