Describe the bug#
Since v5.105.2, a query with placeholderData: keepPreviousData and a select that returns undefined for the placeholder loops while the query is disabled or its new key is still loading, until React throws "Maximum update depth exceeded". Unlike #12532, select does not throw. Still reproducible on v5.107.1 and main; v5.105.1 is fine.
Your minimal, reproducible example#
https://stackblitz.com/github/mooxl/tanstack-query-12574-repro?file=src%2Fmain.jsx
Click the button. Switch @tanstack/react-query to 5.105.1 in package.json and it settles instead.
function Picker() {
const [id, setId] = useState('a')
const { data } = useQuery({
queryKey: ['items', id],
queryFn: () => [id],
enabled: id !== '',
placeholderData: keepPreviousData,
select: (items) => items.find((item) => item === id),
})
return <button onClick={() => setId('')}>{data ?? 'none'}</button>
}
Steps to reproduce#
Render Picker, wait for a, click the button.
Expected behavior#
The result settles as placeholder data (status: 'success', isPlaceholderData: true, data: undefined).
How often does this bug happen?#
Every time
Platform#
Any
Tanstack Query adapter#
react-query
TanStack Query version#
5.107.1
Additional context#
QueryObserver.createResult has no fixed point here. When the previous result was a placeholder, it reuses prevResult.data, which select already mapped to undefined, so the result falls back to pending. The next call computes the placeholder again (success). #12230 makes useQuery call getOptimisticResult and then setOptions on every render, which keeps flipping it. It also reproduces with QueryObserver alone.
We've run into this too. In our case the query isn't disabled. It occurs when the query key changes and the new query is pending. Your example, without
enabledand with an asyncqueryFn:Clicking the button loops while
['items', 'b']is pending, because the placeholder['a']has no match for'b'. Still reproduces on 5.107.1. For now we've pinned to 5.104.4 until a fix lands. Your suggested fix should also fix our case.