#Wha
1 messages · Page 1 of 1 (latest)
If you want to read the search parameters without exporting a component, you can still use the useSearchParams hook within a functional component and then use the value as needed. However, you need to ensure that the component using useSearchParams is wrapped in a Suspense boundary. This is because useSearchParams is a Client Component hook and it requires a Suspense boundary to prevent stale values during partial rendering.
Here's an example of how you can use it:
import { Suspense } from 'react'
import { useSearchParams } from 'next/navigation'
function ComponentUsingSearchParams() {
const searchParams = useSearchParams()
const val = searchParams.get('val')
console.log(val)
// Use the value as needed
return null
}
export default function Home() {
return (
<Suspense fallback={<div>Loading...</div>}>
<ComponentUsingSearchParams />
</Suspense>
);
}
In this example, ComponentUsingSearchParams is a component that uses useSearchParams to get a value from the query string. It's wrapped in a Suspense boundary in the Home component to ensure it's client-side rendered.
If you're not exporting a component but just using it for a value, you can create a secondary component that uses it, or provide a loading.tsx file alongside your page.jsx, which will automatically wrap the exported page with suspense and use the contents of the loading file as the fallback (source (https://github.com/vercel/next.js/issues/67398)).
If you're working with Server Components (Pages), you can use the searchParams prop to access search parameters (source (https://nextjs.org/docs/app/api-reference/functions/use-search-params#pages)).