vercel / next.js

The React Framework
https://nextjs.org
MIT License
122.91k stars 26.28k forks source link

`useSearchParams` requires Suspense wrapper even when not exporting a component #67398

Closed aaronzshey closed 3 days ago

aaronzshey commented 3 days ago

Link to the code that reproduces this issue

https://github.com/aaronzshey/usesearchparams-reproduction/blob/bd514220ce63a6b1b8aeb691711e16245b1ecc70/app/page.tsx#L6

To Reproduce

Current vs. Expected behavior

According to the current documentation, this error should be solved by wrapping a component using useSearchParams in Suspense tags. However, what do I do when I'm not exporting a component, but just using it for a value? For example, something like this:

export default function Home() {
  const val = useSearchParams().get("val");
  console.log(val);
  return (
    <Suspense>
      <main>Hello World</main>
    </Suspense>
  );
}

According to icyJoseph, one could use document.location.search. However, this exposes a whole new host of issues, such as document not being found, etc etc.

Is there a way to resolve this issue while still using useSearchParams? And if so, can it be added to the documentation?

Provide environment information

Operating System:
  Platform: darwin
  Arch: x64
  Version: Darwin Kernel Version 21.6.0: Thu Nov  9 00:38:19 PST 2023; root:xnu-8020.240.18.705.10~1/RELEASE_X86_64
  Available memory (MB): 16384
  Available CPU cores: 8
Binaries:
  Node: 22.3.0
  npm: 10.8.1
  Yarn: 1.22.22
  pnpm: 9.4.0
Relevant Packages:
  next: 14.2.4 // Latest available version is detected (14.2.4).
  eslint-config-next: N/A
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.5.2
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Navigation

Which stage(s) are affected? (Select all that apply)

next build (local)

Additional context

Relevant issue: https://github.com/vercel/next.js/discussions/61654

wyattjoh commented 3 days ago

In this case you should 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.

aaronzshey commented 3 days ago

In this case you should 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.

Where can I find this in the documentation? If it isn't there, would it be acceptable for me to add it?