react-router
react-router copied to clipboard
Updates to search params using `useSearchParams` are not always propagated at the same time to all consumers
Reproduction
https://stackblitz.com/edit/remix-run-remix-8wtcgn?file=app%2Froutes%2F_index.tsx
To reproduce;
- Click
set param mutate currentbutton on any of the components - You'll see that the component's history stacks that list the changes to the search param will be different
To see how it behaves without mutating the passed in current search params;
- Click reset button
- Click
set param (create new URLSearchParams)on any of the components - You'll see that the component's history stacks will look the same
System Info
System:
OS: macOS 14.4.1
CPU: (10) arm64 Apple M1 Pro
Memory: 75.69 MB / 32.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 20.13.1 - /usr/local/bin/node
Yarn: 1.22.19 - ~/.yarn/bin/yarn
npm: 10.5.2 - /usr/local/bin/npm
pnpm: 9.1.3 - /usr/local/bin/pnpm
bun: 1.1.10 - ~/#####REDACTED#####/node_modules/.bin/bun
Watchman: 2024.04.15.00 - /opt/homebrew/bin/watchman
Browsers:
Chrome: 125.0.6422.113
Safari: 17.4.1
Used Package Manager
pnpm
Expected Behavior
When a component updates search params using useSearchParams, all the other components that consume useSearchParams should get the updated value at the same time as the component triggering the change.
Actual Behavior
When setSearchParams is called with an updater function as argument; if this function directly mutates the current URLSearchParams passed to it and returns that, the calling component will get the updated search params value on the first re-render. But the other components that use useSearchParams will get the updated value on the second re-render.
I checked the source code of useSearchParams
https://github.com/remix-run/react-router/blob/main/packages/react-router-dom/index.tsx#L1467
And here is my suggestion:
searchParams resets every time when location.search changes. It means, every time when location.search updates, we are start using old searchParams in our running functions.
Here is demo of the bug
https://codesandbox.io/p/sandbox/aged-smoke-rsxsjx?file=%2Fsrc%2FApp.js%3A20%2C8-20%2C95
On change sp2 while the function running, the value in sp1 in the function not changed.
Hello @brophdawg11, can you see please?
Are there any updates on this issue? This is causing us to use workarounds like forcing re-render after setting the URL search parameters.
This issue was closed by me by mistake, I reopened it now.
This was fixed by https://github.com/remix-run/react-router/pull/12784 in 7.7.0: https://stackblitz.com/edit/remix-run-remix-ecsxatdd