Blog>
Snippets

Custom Hook for API Calls

Create a custom hook that encapsulates the useQuery hook for fetching user data, illustrating how to streamline API calls and improve code reusability.
import { useQuery } from 'react-query';
import { apiClient } from './apiClient';

type User = {
    id: string;
    name: string;
    email: string;
};

type GetUserQueryParams = {
    userId: string;
};

const QUERY_KEY = ['User'];

const fetchUser = async (params: GetUserQueryParams): Promise<User> => {
    const { data } = await apiClient.get(`/users/${params.userId}`);
    return data;
};

export const useGetUser = (params: GetUserQueryParams) => {
    return useQuery<User, Error>(QUERY_KEY, () => fetchUser(params));
};
This code snippet defines a custom hook named useGetUser that encapsulates the useQuery hook from the React Query library. It's used for fetching user data from an API. The hook expects parameters of the GetUserQueryParams type (which includes userId) and returns the data wrapped in the useQuery hook for easy fetching and caching. An external apiClient instance is used for performing the actual API call.
import { useGetUser } from './useGetUser';

type Props = {
    userId: string;
};

const UserComponent = ({ userId }: Props) => {
    const { data: user, isLoading, isError } = useGetUser({ userId });

    if (isLoading) return <div>Loading...</div>;
    if (isError) return <div>Error fetching user</div>;

    return (
        <div>
            <h1>{user?.name}</h1>
            <p>Email: {user?.email}</p>
        </div>
    );
};

export default UserComponent;
This code snippet demonstrates how to use the useGetUser hook within a React component. It defines a UserComponent that takes a userId prop, uses the custom hook to fetch the corresponding user's data, and renders it. The snippet also includes basic error handling and loading state management.