Search params are not available in layouts in Next.js App Router for a specific reason related to performance and rendering behavior. Let me explain:
- Layouts in Next.js App Router are not re-rendered during navigation . This is an intentional design choice to optimize performance.
- When using client-side navigation, Next.js automatically only renders the part of the page below the common layout between two routes 1. This partial rendering approach significantly improves navigation speed.
- Because layouts are not re-rendered during navigation, if they were to receive
searchParams
, these params could become stale after navigation 1. This could lead to inconsistent or outdated information being displayed in the layout.
To illustrate this, consider a scenario where you have a shared layout for multiple pages within a dashboard:
/dashboard
layout.tsx
/settings
page.tsx
/analytics
page.tsx
When navigating from /dashboard/settings
to /dashboard/analytics
, only the page.tsx
in /dashboard/analytics
will re-render. The layout.tsx
in /dashboard
will not re-render because it's shared between these routes 1.
Instead of using searchParams
in layouts, you have two main alternatives:
- Use the Page
searchParams
prop: This is available in your page components and will always have the most up-to-date values . - Use the
useSearchParams
hook: This is a Client Component hook that will re-render on the client with the latestsearchParams
.
By using these alternatives, you ensure that your components always have access to the most current search parameters, maintaining consistency in your application's state.
328d ago