Skip to content

Instantly share code, notes, and snippets.

@dalechyn
Last active November 25, 2024 17:29
Show Gist options
  • Select an option

  • Save dalechyn/1ebd1640f8974f002232ffd4395a2a1c to your computer and use it in GitHub Desktop.

Select an option

Save dalechyn/1ebd1640f8974f002232ffd4395a2a1c to your computer and use it in GitHub Desktop.
query-provider.tsx
'use client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import * as React from 'react'
// import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental'
// import superjson from 'superjson'
import { hashFn, structuralSharing } from '~/_lib/query'
function makeQueryClient() {
return new QueryClient({
defaultOptions: {
queries: {
structuralSharing: structuralSharing,
queryKeyHashFn: hashFn,
retry: 3,
retryDelay: (count) => {
return ~~(1 << count) * 1000
},
// With SSR, we usually want to set some default staleTime
// above 0 to avoid refetching immediately on the client
staleTime: 5000
}
}
})
}
let browserQueryClient: QueryClient | undefined
function getQueryClient() {
if (typeof window === 'undefined') {
// Server: always make a new query client
return makeQueryClient()
}
// Browser: make a new query client if we don't already have one
// This is very important so we don't re-make a new client if React
// supsends during the initial render. This may not be needed if we
// have a suspense boundary BELOW the creation of the query client
if (!browserQueryClient) browserQueryClient = makeQueryClient()
return browserQueryClient
}
export function ReactQueryProvider(props: { children: React.ReactNode }) {
const queryClient = getQueryClient()
// NOTE: Avoid useState when initializing the query client if you don't
// have a suspense boundary between this and the code that may
// suspend because React will throw away the client on the initial
// render if it suspends and there is no boundary
return (
<QueryClientProvider client={queryClient}>
{/* <ReactQueryStreamedHydration transformer={superjson}> */}
{props.children}
{/* </ReactQueryStreamedHydration> */}
<ReactQueryDevtools buttonPosition='bottom-left' />
</QueryClientProvider>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment