Explain the basic structure of a `useQuery` hook

Beginner

Answer

The useQuery hook accepts a configuration object with key properties:

const { data, isLoading, error, isError, isSuccess } = useQuery({
  queryKey: ['posts', userId], // Unique identifier for the query
  queryFn: () => fetchPosts(userId), // Function that returns a promise
  enabled: !!userId, // Optional: conditionally enable the query
  staleTime: 5 * 60 * 1000, // Optional: how long data stays fresh
  refetchOnWindowFocus: false // Optional: disable refetch on window focus
});

Key properties:

  • queryKey: Unique identifier used for caching and invalidation
  • queryFn: Async function that fetches the data
  • enabled: Boolean to conditionally run the query
  • staleTime: Time in milliseconds before data is considered stale
    Return values:
  • data: The fetched data
  • isLoading: True during the first fetch
  • error: Error object if the query failed
  • isError/isSuccess: Boolean states for handling different scenarios