Table of contents
Short answer
You can't. Because you shouldn't.
Long answer
In Next.js, layouts stay the same when you switch routes, so they don't re-render. This helps keep the state and makes things faster by not re-rendering. But it also means layouts can't directly access search parameters (searchParams
) because these can change with navigation and would need the layout to re-render to show the new state.
You may think it's a stupid idea. But it's actually desired. For example, if you have a Navigation component at the top of your layout, you don't want it to re render every time you navigate to a new route.
But I really need it
One workaround is to use client components. To be fair, it's not a workaround, but wherever you need the search params, you would use a client component.
'use client';
import { useSearchParams } from 'next/navigation';
function SearchComponent() {
const searchParams = useSearchParams();
const search = searchParams.get('search');
return <div>Search: {search}</div>;
}
export default function Layout({ children }) {
return (
<div>
<SearchComponent />
{children}
</div>
);
}
If you need to conditionally render things, return null inside the client component when, e.g., search params aren't there.