Custom Query Hook for Reusable API Calls
Creating a custom hook that encapsulates the useQuery hook for fetching a specific resource, making the API call reusable and easy to manage.
import { useQuery } from 'react-query';
import axios from 'axios';
// fetcher function to get user data from API
const fetchUserById = async (userId) => {
const { data } = await axios.get(`https://example.com/api/users/${userId}`);
return data;
};
// Custom hook using useQuery for fetching user data by ID
export const useUser = (userId) => {
return useQuery(['user', userId], () => fetchUserById(userId), {
// You can specify React Query options here
staleTime: 1000 * 60 * 5, // 5 minutes
});
};
This custom query hook, named useUser, abstracts away the logic for fetching user data by a specific ID using React Query's useQuery hook and Axios for making the API call. It takes a userId as an argument and returns the query object from useQuery. The query key is an array with 'user' and the userId, ensuring a separate cache entry for each user. We also set a staleTime of 5 minutes, indicating how long the fetched data is considered fresh.