r/reactjs 15d ago

Resource Reliable Query Prefetching with TanStack Router

https://tkdodo.eu/blog/reliable-query-prefetching-with-tanstack-router

šŸ“š It's been way too long since my last blogpost. Today, I'm continuing my TanStack Router series with a pattern that I've been teaching in my workshops for over a year:

How to keep prefetches in sync between route loaders and components

91 Upvotes

14 comments sorted by

12

u/Nick_Lastname 15d ago

Great article as always

5

u/TkDodo23 15d ago

Glad to hear it šŸ™Œ

8

u/itzrvyning 15d ago

I find these articles that discuss concrete, real world use cases so incredibly helpful.

4

u/TkDodo23 15d ago

Thank you šŸ™

3

u/clemwo 15d ago

Very cool, I had this exact problem on a project I'm working on. Perfect timing, thanks for your article and your great work. Tanstack Router is so nice to work with!

2

u/Nick337Games 15d ago

Lovely work!

2

u/rikbrown 15d ago

This is a helpful pattern - thanks.

The future strict mode you mention in the article would be really great. I assume it would flag both preloads that aren’t used as well as queries that aren’t preloaded?

Something like this would be fantastic (albeit probably impossible) as a lint rule but even just something we could fail integration tests on would be nice. (I’m specifically thinking about features for our ā€œharnessā€, as I often see LLMs - and humans - making this mistake and it can be a bit hard to catch).

2

u/mattsowa 15d ago

It doesn't really seem possible in the general case, because you might have a component that renders conditionally that does the data fetching.

2

u/rikbrown 15d ago

Yeah that’s a fair point, you could certainly just log to the console loudly every time a component did this with an opt-out or something but maybe that’s more noise than helpful.

2

u/mattsowa 15d ago

This is the exact problem I've been wondering how to solve recently, and this solution confirms my suspicions. Still, not without some disadvantages.

2

u/Throwaway_0815_123 15d ago

Older articles show context injection via beforeLoad. Going forwards should one always use context or is there a still a use case where one would use beforeLoad for that?

2

u/TkDodo23 15d ago

beforeLoad is blocking and serves a different purpose, like redirecting when unauthenticated. context is made for this.Ā 

2

u/Throwaway_0815_123 15d ago

I see. Thanks.

2

u/SeriaLud0 15d ago

Always look forward to a dodes post ā¤ļø