Skip to content

Commit c0bcdb6

Browse files
committed
Add detailed Router caching example with loaderDeps
- Explain how Router automatically caches loader data by route + params - Add loaderDeps example showing search param dependencies in cache key - Show navigation flow and cache hit/miss behavior
1 parent 9f7e0ad commit c0bcdb6

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/blog/composite-components.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,8 @@ Streams are universal. They work with:
164164

165165
### In a route loader
166166

167+
TanStack Router caches loader data automatically. The cache key is the route path plus its params—when params change, the loader refetches:
168+
167169
```tsx
168170
export const Route = createFileRoute('/posts/$postId')({
169171
loader: async ({ params }) => ({
@@ -183,6 +185,33 @@ function PostPage() {
183185
}
184186
```
185187

188+
Navigate from `/posts/abc` to `/posts/xyz` and the loader runs again because `$postId` changed. Navigate back to `/posts/abc` and Router serves the cached server component instantly (within the default `gcTime`).
189+
190+
For dependencies beyond route params, use `loaderDeps` to include search params or other reactive values in the cache key:
191+
192+
```tsx
193+
export const Route = createFileRoute('/posts/$postId')({
194+
loaderDeps: ({ search }) => ({
195+
tab: search.tab,
196+
sort: search.sort
197+
}),
198+
loader: async ({ params, deps }) => ({
199+
Post: await getPost({
200+
data: {
201+
postId: params.postId,
202+
tab: deps.tab,
203+
sort: deps.sort
204+
}
205+
}),
206+
}),
207+
component: PostPage,
208+
})
209+
```
210+
211+
Now the cache key includes both the route param and search params. Change `?tab=comments` to `?tab=related` and the server component refetches. Change back and you get a cache hit.
212+
213+
**Router handles this automatically.** No manual cache keys, no query configuration. The server component is fetched when dependencies change and cached when they don't.
214+
186215
### With Query caching
187216

188217
Because server components are just data, they integrate naturally with TanStack Query's caching model. The query key determines cache identity—include route params and the cache automatically invalidates when they change:

0 commit comments

Comments
 (0)