Skip to content
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

[Bug]: Functional updates to useSearchParams don't get updated values #11752

Closed
darreneng opened this issue Jun 28, 2024 · 2 comments
Closed
Labels

Comments

@darreneng
Copy link

What version of React Router are you using?

6.24.0

Steps to Reproduce

Functional updates to the search params using urlSearchParams don't seem to work in the same way as useState does. When making consecutive functional updates using setState, each time the function is called it receives the most up-to-date value. Ex.

const [count, setCount] = useState(0)
...
setCount(prevCount => prevCount + 1) // prevCount is 0
setCount(prevCount => prevCount + 1) // prevCount is 1

The difference in behavior is also shown in this stackblitz:

https://stackblitz.com/edit/github-rmemxe?file=src%2FApp.tsx

  1. In the stackblitz link shown above, click "increment by 2" by "React state based count"
  2. Observe that the count changes from 0 to 2. Subsequent counts will increment by 2
  3. Click "increment by 2" by "search param based count"

Expected Behavior

The "search param based count" should increment by 2

Actual Behavior

The "search param based count" only increments by 1

@darreneng darreneng added the bug label Jun 28, 2024
@timdorr
Copy link
Member

timdorr commented Jun 29, 2024

setSearchParams is simply calling navigate under the hood. What that means is the set operation needs to go through a full routing/render cycle until the updated data is made available, even to the function form. You should combine your calls to setSearchParams.

@timdorr timdorr closed this as completed Jun 29, 2024
@darreneng
Copy link
Author

@timdorr thanks for replying. That's fair, but what's the purpose of providing the callback API then? It seems misleading to provide this API if this behavior isn't supported - if we ever need to read params we should only use the first element of useSearchParams()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants