new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

TanStack Query · React · all subjects

suspense

33 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

useQuery().promise with React.use() example

const queryClient = new QueryClient({ defaultOptions: { queries: { experimental_prefetchInRender: true, }, }, }) import React from 'react' import { useQuery } from '@tanstack/react-query' import { fetchTodos, type Todo } from './api' function TodoList({ query }: { query: UseQueryResult<Todo[]> }) { const data = React.use(query.promise) return ( <ul> {data.map((todo) => ( <li key={todo.id}>{todo.title}</li> ))} </ul> ) } export function App() { const query = useQuery({ queryKey: ['todos'], queryFn: fetchTodos }) return ( <> <h1>Todos</h1> <React.Suspense fallback={<div>Loading...</div>}> <TodoList query={query} /> </React.Suspense> </> ) } This experimental pattern allows passing a useQuery result's promise to React.use() for suspense integration.

Suspense-dedicated hooks in React Query

React Query provides three dedicated hooks for use with React's Suspense for Data Fetching: useSuspenseQuery, useSuspenseInfiniteQuery, and useSuspenseQueries. Additionally, you can use useQuery().promise combined with React.use() (experimental).

Suspense mode replaces status and error handling

When using suspense mode, status states and error objects are not needed because errors are handled by React error boundaries and loading states are handled by React Suspense components with fallback props.

useSuspenseQuery example

import { useSuspenseQuery } from '@tanstack/react-query' const { data } = useSuspenseQuery({ queryKey, queryFn }) This hook guarantees that data is defined in TypeScript because errors and loading states are handled by Suspense and ErrorBoundaries.

Cannot conditionally enable/disable suspense queries

You cannot conditionally enable or disable a suspense query. This limitation generally should not be a problem for dependent queries because with suspense, all queries inside one component are fetched serially.

placeholderData does not exist in suspense mode

The placeholderData option is not available for suspense queries. To prevent the UI from being replaced by a fallback during an update, wrap updates that change the QueryKey into startTransition.

Default throwOnError behavior in suspense

Not all errors are thrown to the nearest Error Boundary by default. Errors are only thrown if there is no other data to show. If a query ever successfully got data in the cache, the component will render even if data is stale. The default throwOnError is: throwOnError: (error, query) => typeof query.state.data === 'undefined'

Manually throw errors in suspense mode

import { useSuspenseQuery } from '@tanstack/react-query' const { data, error, isFetching } = useSuspenseQuery({ queryKey, queryFn }) if (error && !isFetching) { throw error } // continue rendering data Since throwOnError cannot be changed (it would allow data to become undefined), you must manually throw errors if you want all errors to be handled by Error Boundaries.

useQueryErrorResetBoundary hook usage

import { useQueryErrorResetBoundary } from '@tanstack/react-query' import { ErrorBoundary } from 'react-error-boundary' const App = () => { const { reset } = useQueryErrorResetBoundary() return ( <ErrorBoundary onReset={reset} fallbackRender={({ resetErrorBoundary }) => ( <div> There was an error! <Button onClick={() => resetErrorBoundary()}>Try again</Button> </div> )} > <Page /> </ErrorBoundary> ) } This hook resets any query errors within the closest QueryErrorResetBoundary. If no boundary is defined, it resets them globally.

Fetch-on-render vs Render-as-you-fetch

React Query in suspense mode works out of the box as a Fetch-on-render solution, where queries trigger when components mount and suspend. To implement Render-as-you-fetch (starting queries before components mount), use prefetching on routing callbacks and/or user interaction events.

throwOnError option for mutations

If you want mutations to propagate errors to the nearest error boundary similar to queries, you can set the throwOnError option to true.

experimental_prefetchInRender option

To enable the useQuery().promise and React.use() experimental feature, set the experimental_prefetchInRender option to true when creating your QueryClient.

QueryErrorResetBoundary reset function

QueryErrorResetBoundary provides a reset function through its render prop that can be passed to ErrorBoundary's onReset prop to reset any query errors within the component boundaries.

QueryErrorResetBoundary component purpose

QueryErrorResetBoundary is used to reset query errors when using suspense or throwOnError in queries. It allows queries to retry when re-rendering after an error occurs.

QueryErrorResetBoundary with ErrorBoundary integration

To use QueryErrorResetBoundary with react-error-boundary, wrap the ErrorBoundary component inside QueryErrorResetBoundary and pass the reset function to the ErrorBoundary's onReset prop.

usePrefetchQuery required options

usePrefetchQuery requires two options: queryKey (a QueryKey, required) and queryFn (a function with signature (context: QueryFunctionContext) => Promise<TData>, required only if no default query function has been defined). All other options that can be passed to queryClient.prefetchQuery are also supported.

usePrefetchQuery hook signature and purpose

usePrefetchQuery is a React hook that prefetches a query during render. It takes options as a parameter and does not return anything. It should be used before a suspense boundary that wraps a component that uses useSuspenseQuery.

useSuspenseQueries TypeScript typing same as useQueries

The same TypeScript select parameter typing limitations and workarounds that apply to useQueries also apply to useSuspenseQueries.

useSuspenseInfiniteQuery options differences

useSuspenseInfiniteQuery accepts the same options as useInfiniteQuery except it does not accept: suspense, throwOnError, enabled, or placeholderData.

useSuspenseInfiniteQuery query cancellation caveat

Query cancellation does not work with useSuspenseInfiniteQuery.

useSuspenseInfiniteQuery basic usage

useSuspenseInfiniteQuery is invoked with options and returns a result object. It works like useInfiniteQuery but with suspense integration.

useSuspenseInfiniteQuery return value differences

useSuspenseInfiniteQuery returns the same object as useInfiniteQuery with these differences: the data property is guaranteed to be defined, isPlaceholderData is not present, and status is either 'success' or 'error' with derived flags set accordingly.

useSuspenseQueries remounts after all queries complete

The component using useSuspenseQueries will only re-mount after all queries have finished loading. If a query has gone stale while waiting for all queries to complete, it will be fetched again at re-mount.

useSuspenseQueries select option typing caveat

The select typing caveat from useQueries applies to useSuspenseQueries as well. To maintain type inference with the select parameter, either annotate the select parameter explicitly or use the queryOptions helper.

useSuspenseQueries options restrictions

useSuspenseQueries accepts the same options as useQueries, except that each query cannot have the following properties: suspense, throwOnError, enabled, or placeholderData.

useSuspenseQueries return value structure

useSuspenseQueries returns the same structure as useQueries, except that for each query: data is guaranteed to be defined, isPlaceholderData is missing, and status is either success or error with derived flags set accordingly.

useSuspenseQueries prevent re-fetching stale queries

To avoid re-fetching queries that have gone stale while waiting for all queries to complete, set a high enough staleTime value.

useSuspenseQuery return value - isPlaceholderData is missing

useSuspenseQuery return object does not include the isPlaceholderData property that is present in useQuery.

useSuspenseQuery return value - status is success or error only

useSuspenseQuery status is either 'success' or 'error'. It cannot be 'loading' or 'idle'. The derived status flags are set accordingly.

useSuspenseQuery hook signature

useSuspenseQuery is called with options object and returns a result object: const result = useSuspenseQuery(options)

useSuspenseQuery options vs useQuery

useSuspenseQuery accepts the same options as useQuery, except throwOnError, enabled, and placeholderData are not available.

useSuspenseQuery return value - data is guaranteed defined

useSuspenseQuery returns the same object as useQuery, but the data property is guaranteed to be defined (non-null).

useSuspenseQuery cancellation does not work

Query cancellation does not work with useSuspenseQuery.

Give your agent this brain