When Is The Route Dynamically Rendered and How Is It Cached?
When Is The Route Dynamically Rendered
- Export route config as "const dynamic = 'forced-dynamic'", "const revalidate = 0"
- Using functions like headers, cookies, searchParams or using useSearchParams() hook inside of client component make the route becomes dynamic. This cause it to traverse up to the first <Suspense> boundary and render that entire segment dynamically. Therefore, it is recommended to wrap the client component inside a <Suspens> boundary
How Is It Cached
1) For Dynamic Segement(app/post/[id]/page.js)
paths provided by generateStaticParams are cached in the Full Route Cache at build time(the path that weren't cached at build time will cached in request time when the first time they are visited).
To disabling the caching at request time, set following option in a route segment. This config option make only the path provided by generatedStaticParams served not other route(404)
javascript
1export const dynamicParams = false
2) For 3rd party Library
You can use cache to manually memoize data requests function that not suitable for fetch API, for example, database client, CMS client, or GraphQL client.
- cache function only avaliable at server component
- React will invalidate the cache for all memoized functions for each server request
javascript
1import { cache } from 'react'
2import db from '@/lib/db'
3
4export const getItem = cache(async (id) => {
5 const item = await db.item.findUnique({ id })
6 return item
7})