Question about stable data
I got a general question regarding if data is considered a stable reference here whenever the key changes in a component this hook was mounted on. the data was returned as a new reference every time the key changes even though the data is exactly the same unless I add
select: useCallback((data) => data?.testing, []),
as an option. thanks!4 Replies
continuing-cyan•16mo ago
can you show this in a sandbox example please? I think it should be structurally shared, but I'd have to dig into what happens when the key changes
correct-apricotOP•16mo ago
https://codesandbox.io/p/sandbox/hardcore-pond-rw8gnz?file=%2Fsrc%2FApp.js
sure, here is one!
my first time using the sandbox, let me know if you need me to modify anything. the useEffect's doesn't run when the test button is clicked if both palceholderData and select: useCallback((d) => d, []) are provided. without select, it would run again
continuing-cyan•16mo ago
okay I think I see what's happening:
1) data is usually structurally shared within one cache entry. So if I refetch for the same entry, it will be referentially stable.
2) when we use placeholderData, we'll get that data while transitioning between queries. In this case, while the next number is pending, we'll also get the structurally same data from the previous query.
3) but then, after the query with the next number resolves, we have nothing to compare it against - it's a new cache entry that will be shared against
undefined
, so you'll get that new object.
4) if you have select, everything will run through select and the result of select is always structurally shared again. So that's why it works with select.
---
what we could do is always run through structural sharing if placeholderData is defined, even if a new entry is no longer pending, so that you could get your real result shared with the result from the previous key. I'm not sure if that's such a good idea thoughcorrect-apricotOP•16mo ago
Thanks so much for the explanation!! We have a few backend API that potentially returns the same data even if the id is different which is how I ran into this question. I can also help contribute if you think it is something we should support based on a flag or setting it as the default option for placeholderData. Thanks!