Paginated results
A page number is included in queryKey and users should not see the list disappear between page requests.
TanStack · Function
Keeps a query's previous result visible as placeholder data while a changed query key fetches its new result. Pass the function to placeholderData.
keepPreviousData is a generic identity function intended for a query's placeholderData option. When the query key changes, it returns the prior result so the UI can continue displaying it until the replacement data arrives.
function keepPreviousData<T>(previousData: T | undefined): T | undefined;| Name | Type | Description |
|---|---|---|
previousData | T | undefined | Data associated with the previous query key, supplied by the observer; it may be undefined. |
The previous data unchanged, or undefined when no previous data is available.
import { keepPreviousData, useQuery } from '@tanstack/react-query'
function Projects({ page }: { page: number }) {
const query = useQuery({
queryKey: ['projects', page],
queryFn: () => fetch(`/api/projects?page=${page}`).then(r => r.json()),
placeholderData: keepPreviousData,
})
return <pre>{JSON.stringify(query.data, null, 2)}</pre>
}Passing keepPreviousData as placeholderData preserves the prior result while the query for the changed key is fetching.
A page number is included in queryKey and users should not see the list disappear between page requests.
Filters or another key component changes and the replacement request should transition without an empty intermediate view.
keepPreviousData has the signature keepPreviousData<T>(previousData: T | undefined): T | undefined. It receives the prior query-key data from the observer and returns that value unchanged.
Follow-up: What happens if no prior result exists? The function returns undefined, so the query has no previous data to display.
Pass it as the query's placeholderData option. When a key changes, the previous result remains visible instead of the data becoming undefined while the new request runs.
Follow-up: Why is the query key still significant? A changed key still identifies and fetches distinct query data; keepPreviousData only bridges the display during the transition.
It is useful for paginated queries whose page number is part of queryKey. The old page can remain rendered until the newly requested page arrives.
Follow-up: How can an application distinguish transitional data? Track the query's fetching state alongside the displayed data, rather than assuming the retained result is current.
placeholderDatauseQueryQueryObserver