Skip to content

fix(react-router): fix useSearchParams when used together w/ useBlocker #12784

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,7 @@
- yionr
- yracnet
- ytori
- yuhwan-park
- yuleicul
- zeromask1337
- zheng-chuang
4 changes: 3 additions & 1 deletion packages/react-router/lib/dom/lib.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1425,7 +1425,9 @@ export function useSearchParams(
let setSearchParams = React.useCallback<SetURLSearchParams>(
(nextInit, navigateOptions) => {
const newSearchParams = createSearchParams(
typeof nextInit === "function" ? nextInit(searchParams) : nextInit
typeof nextInit === "function"
? nextInit(new URLSearchParams(searchParams))
: nextInit
Comment on lines +1428 to +1430
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if we want to add the URLSearchParams call here or in getSearchParamsForLocation 🤔

CC/ @brophdawg11

Copy link
Author

@yuhwan-park yuhwan-park Apr 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The getSearchParamsForLocation function already returns a new URLSearchParams object each time.
Here's what's happening in the flow that causes the bug:

  1. setSearchParams executes (this is where searchParams changes)
setSearchParams((prev) => {
    prev.set("mode", "edit");
    return prev;
  })
  1. router.navigate() runs
  2. It gets blocked by useBlocker
  3. Even though the location.pathname hasn't changed, the searchParams returned by useSearchParams remains in the modified state

Because of this flow, I think we need to create a deep copy of the URLSearchParams before passing it to the nextInit function - regardless of how nextInit is implemented - to ensure it behaves as intended.

);
hasSetSearchParamsRef.current = true;
navigate("?" + newSearchParams, navigateOptions);
Expand Down