useSearchParams() should be wrapped in a suspense boundary

date
Jan 24, 2024
slug
use-search-params-should-be-wrapped-in-a-suspense-boundary
status
Published
tags
Shorts
Frontend
Next.JS
summary
Next.js v14.1.0 後,experimental flag missingSuspenseWithCSRBailout 預設從 false 變成 true …
type
Post
Next.js v14.1.0 後,experimental flag missingSuspenseWithCSRBailout 預設從 false 變成 true,變成如果需要 pre-build 的 Page / Layout 有用到 useSearchParams() 但沒有在外層包上 <Suspense /> 的話,會直接在 build 時噴一個 BailoutToCSRError,Error Log 如下:
“useSearchParams() should be wrapped in a suspense boundary at page "...". Read more: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout
 
而會有這樣的行為主要是避免開發者在錯誤的寫法下 build 出一個 Client Side Render Only 的頁面,但感覺有點激進。雖然目前可以先手動把這個 experimental flag 關掉,但根據官方文件上的說法,未來會把這個 flag 直接拿掉,看來還是能加 Suspense 就先加吧
 
但相對應的在設計 custom hook 上,感覺就更不適合拿 useSearchParams() 來再封裝,畢竟外層很難 aware 裡面的實作。不過保險的解法可能就是在 Page 層都包個 Suspense,至少能讓他 build 過 🚬

© maxam 2023 - 2024