Best Practices with React Query: Reusable Custom Hooks

Create reusable custom hooks for data fetching with React Query. This simplifies the process, making your React app more efficient and maintainable.

What is React Query (Tanstack Query) ?

React Query is a data-fetching and state management library for React applications. It simplifies the process of fetching, caching, and synchronizing server data, providing essential features like automatic updates, retries, pagination, and background fetching for enhanced user experiences and efficient performance.

Why use custom hooks?

Custom hooks with React Query simplify data fetching, increase code reusability, and enhance state management in React applications, leading to cleaner and more efficient code.

Example

Here's an example on how to create a custom hook with React Query:

import { useQuery } from '@tanstack/react-query';
import { FetchUserProps } from '@/types';
import { fetchUserApiCall } from '@/api';

export const useFetchUser = () => {
  const { data, isLoading, isError } = useQuery<FetchUserProps, Error>(
    ['fetchUser'],
    fetchUserApiCall
  );

  return {
    data,
    isLoading,
    isError,
  };
};

How to use it

Import the custom hook to you component and start using it by destructuring the object from useFetchUser().

// MyComponent.tsx

import { useFetchUser } from '@/hooks/useFetchUser';

const MyComponent = () => {
    const { data, isLoading, isError } = useFetchUser();

    if (isLoading) {
        return <div>Loading...</div>;
    }

    if (isError) {
        return <div>Error</div>;
    }

    return <div>{data}</div>;
};

Structure

The hooks should be in a hooks folder and have names that start with "use".

├── hooks
│   ├── useFetchUser.tsx