[v4] Measure loading time of a query using QueryCache

Duplicated from https://github.com/TanStack/query/discussions/6730

Hey,
I'm implementing a hook that observes all queries coming to react-query and detects the ones that have poor latency. While implementing I stumbled upon an issue - loading queries have dataUpdatedAt always at 0 (because they're loading so there's no data yet). Because of that, I can only detect slow-loading queries only on a page reload when they're picked up from query cache.

How would I measure loading time of a query without a page reload, and if it takes more time to load than usual, to commit some kind of action? (in this case push a query to array)

This is my current implementation:

import { notifyManager, QueryCache, useQueryClient } from '@tanstack/react-query'
import { useCallback, useState } from 'react'

const SLOW_THRESHOLD = 2500

const getSlowQueries = (queryCache: QueryCache, renderedAt: number) => {
  const queries = queryCache.getAll()
  let slowQueries = 0

  queries.forEach((query) => {
    const { dataUpdatedAt, status } = query.state
    const elapsedTime = Date.now() - Math.max(dataUpdatedAt, renderedAt)

    if (query.getObserversCount() > 0) {
      if (elapsedTime > SLOW_THRESHOLD && status === 'loading') {
        slowQueries += 1
      }
    }
  })

  return slowQueries
}

export const useHasLatencyProblems = () => {

  const queryClient = useQueryClient()
  const queryCache = queryClient.getQueryCache()

  const [renderedAt] = useState(() => Date.now())

  const slowQueriesCount = useSyncExternalStore(
    useCallback(
      (onStoreChange) => {
        return queryCache.subscribe(() => {
          notifyManager.batchCalls(onStoreChange)
          setTimeout(() => {
            notifyManager.batchCalls(onStoreChange)
          }, SLOW_THRESHOLD)
        })
      },
      [queryCache],
    ),
    () => getSlowQueries(queryCache, renderedAt),
    () => getSlowQueries(queryCache, renderedAt),
  )
}
GitHub
Hey, I'm implementing a hook that observes all queries coming to react-query and detects the ones that have poor latency. While implementing I stumbled upon an issue - loading queries have data...
[v4] Measure loading time of a query using QueryCache · TanStack qu...
Was this page helpful?