What I Learned Today About tanstack query's initialPageParam

자손킴 @jasonkim@hackers.pub

TIL: In tanstack query's useInfiniteQuery, the initialPageParam is recorded as pageParams[0] during the first render, and that value continues to be reused as long as the cache connected with the same queryKey is maintained.

Therefore, even if you call useInfiniteQuery with different initialPageParam values from different components, if the queryKey is the same, it will be fixed to the initialPageParam that was called first. This means that if you need different starting cursors, you should specify different queryKeys.

While this behavior is natural and logical once you understand it, I think it's a design that can be confusing if you're not familiar with it. I wish the fact that initialPageParam is strongly coupled with queryKey was better expressed as a type constraint in InfiniteQueryOptions.

Conclusion: If you need bidirectional cursor-based pagination, maybe use Relay(?)

6

No comments

If you have a fediverse account, you can comment on this article from your own instance. Search https://hackers.pub/ap/articles/0197a20e-c8f4-730a-a148-74650d91ff1f on your instance and reply to it.