[Bug]: Make setSearchParams stable?
Author: kentcdoddsCreated Jan 26, 2023Updated Aug 25, 2026
Labelsbugpkg:react-router
What version of React Router are you using?
6.7.0
Steps to Reproduce
- Use
setSearchParamsin anything that needs a dependency array and add it to avoid issues. - Notice that the presence of
setSearchParamsin the dependency array triggers the useEffect any time the searchParams change (for example) to run again
Expected Behavior
I expect to be able to use setSearchParams in a useEffect and not have that useEffect re-run just because search params changed.
Actual Behavior
This is happening because setSearchParams allows you to pass a function callback which receives the current searchParams so setSearchParams changes whenever the searchParams change. This is a nice API, but leads to unexpected re-runs of things using setSearchParams.
An alternative is to use a ref to keep track of the latest searchParams and pass that ref.current instead so searchParams doesn't need to be listed in the nextInit call. I can't think of a scenario where this would break anything.
The code I'm talking about is here:
Source: remix-run/react-router