T
TanStack17mo ago
stormy-gold

useQuery data on refetch

Hello, does useQuery do a deep comparison (or something similar) before updating/reassigning the data attribute? for example if I do:
const query = useQuery({
queryKey: ['someData'],
queryFn: () => fetchSomeData()
})

React.useEffect(() => {
console.log("HELLO")
}, [query.data])

return <button onClick={() => query.refetch()}>Click Me</button>
const query = useQuery({
queryKey: ['someData'],
queryFn: () => fetchSomeData()
})

React.useEffect(() => {
console.log("HELLO")
}, [query.data])

return <button onClick={() => query.refetch()}>Click Me</button>
Then HELLO only prints if the data changes. Given object reference changes trigger useEffect when used as a dependency, my intuition is that HELLO would print every time I click the button, the queryFn reassigning data on success, but this is not the case. If I were to change the data returned by fetchSomeData (say, I make a change in the db), then HELLO is printed, giving me the impression that react query only reassigns data/the object reference after a deep comparison or something like that. Can anyone explain why this is the case? Is the underlying implementation of why this happens explained in the docs? If so can I get a link? Thanks!
3 Replies
optimistic-gold
optimistic-gold16mo ago
React Query Render Optimizations
An advanced guide to minimize component re-renderings when using React Query
optimistic-gold
optimistic-gold16mo ago
There's an answer you are looking for with a good detailed explanation.
stormy-gold
stormy-goldOP16mo ago
thank you! looks like structuralSharing is what I was referring to. Thanks again!

Did you find this page helpful?