Created
January 12, 2026 08:01
-
-
Save Temzasse/7c4f2fc16b1265c7289ee9d75589608e to your computer and use it in GitHub Desktop.
Enhanced version of `useReadQuery` in Apollo Client for better DX with Suspense
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useDeferredValue } from "react"; | |
| import { useSpinDelay } from "spin-delay"; | |
| import { | |
| useReadQuery as useApolloReadQuery, | |
| type QueryRef, | |
| } from "@apollo/client/react"; | |
| /** | |
| * Enhanced version of Apollo's `useReadQuery` hook to stop the hook from | |
| * suspending when `queryRef` changes and instead return a `isSuspending` | |
| * flag that can be used to shown an inline loading indicator. | |
| */ | |
| export function useReadQueryDeferred<TData>(queryRef: QueryRef<TData>) { | |
| const deferredQueryRef = useDeferredValue(queryRef); | |
| const result = useApolloReadQuery(deferredQueryRef); | |
| /** | |
| * Add smart delay to prevent spinner flickering when variables change, | |
| * and tell when the query is suspending so that we can show an inline | |
| * loading indicator. | |
| * | |
| * Note: expose both `isSuspending` and `isSuspendingDelayed` flags | |
| * so that the caller can choose whether to use the delay or not. | |
| */ | |
| const isSuspending = deferredQueryRef !== queryRef; | |
| const isSuspendingDelayed = useSpinDelay(deferredQueryRef !== queryRef); | |
| return { ...result, isSuspending, isSuspendingDelayed }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment