Skip to content

[Bug]: Make setSearchParams stable? #9991

Open

Description

@kentcdodds

What version of React Router are you using?

6.7.0

Steps to Reproduce

  1. Use setSearchParams in anything that needs a dependency array and add it to avoid issues.
  2. Notice that the presence of setSearchParams in 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:

let setSearchParams = React.useCallback<SetURLSearchParams>(
(nextInit, navigateOptions) => {
const newSearchParams = createSearchParams(
typeof nextInit === "function" ? nextInit(searchParams) : nextInit
);
hasSetSearchParamsRef.current = true;
navigate("?" + newSearchParams, navigateOptions);
},
[navigate, searchParams]
);

Activity

  1. timdorr commented on Jan 27, 2023

    @timdorr
    Member

    Some historical context on this:

    #9304
    #9912
    #8908 / #9851

  2. max-pcentra commented on Jan 29, 2023

    @max-pcentra

    Also, calling setSearchParams will re-render the whole route. It would be very helpful if at least there would be some sort of flag on each route config, similar to shouldRevalidate, that let's you opt out of such re-renders.

  3. zhengjitf commented on Feb 7, 2023

    @zhengjitf

    I feel that all functions in hooks, especially those we’ll call in other hooks or as props to a component, are supposed to be stable. we just need to be able to get the latest states when these functions are called.

    The following is a simple solution to create stable functions:

    /* in a hook */
    
    const fn = { /*... */ }
    
    const fnRef = useRef(fn)
    fnRef.current = fn
    const stableFn = useCallback((...args) => fnRef.current(...args), [])
    
    // then, we can use stableFn
  4. github-actions commented on Apr 17, 2023

    @github-actions
    Contributor

    This issue has been automatically marked stale because we haven't received a response from the original author in a while 🙈. This automation helps keep the issue tracker clean from issues that are not actionable. Please reach out if you have more information for us or you think this issue shouldn't be closed! 🙂 If you don't do so within 7 days, this issue will be automatically closed.

  5. dennisameling commented on Apr 17, 2023

    @dennisameling

    Please don't close, I literally ran into this issue today 🙏🏼

  6. jamesa3 commented on Apr 18, 2023

    @jamesa3

    We are still affected by this bug. This issue should not be closed until a fix is published.

  7. KostiantynO commented on May 16, 2023

    @KostiantynO

    I use useCallback and it works!

    const updateSearchParams = useCallback(setSearchParams, []); 

    Please kindly consider to make updateFunction a stable reference :)

  8. maastrich commented on Jun 1, 2023

    @maastrich

    Also, if multiple updates happen in the same render cycle, using the new value as a dependency of the callback causes it to no be provided within the prev param of the n+1 setSearchParams call

  9. lucabergamini commented on Jun 2, 2023

    @lucabergamini

    This is what I'm currently using as a workaround (following @zhengjitf stable function suggestion):

    import { useCallback, useEffect, useRef } from "react";
    import { useSearchParams as useSearchParamsOrig } from "react-router-dom";
    
    export function useSearchParams() {
      const [searchParams, setSearchParams] = useSearchParamsOrig();
      // Store a reference to the setter
      const setSearchParamsRef = useRef(setSearchParams);
      // Update the reference when the setter changes
      useEffect(() => {
        setSearchParamsRef.current = setSearchParams;
      }, [setSearchParams]);
      // Return a stable setter (which has no dep on searchParams)
      const setSearchParamsStable = useCallback(
        (...args: Parameters<typeof setSearchParams>) =>
          setSearchParamsRef.current(...args),
        []
      );
      return { searchParams, setSearchParams: setSearchParamsStable };
    }

    in case anybody is looking for the same workaround. It works for my use case, but I've not tested corner cases.

  10. maastrich commented on Jun 6, 2023

    @maastrich

    @lucabergamini useEffect is no good, it would be best at the root off the component as the ref would be instantly updated instead of waiting for the render cycle to end in order to run the effects.

  11. lucabergamini commented on Jun 6, 2023

    @lucabergamini

    Do you mean a setSearchParamsRef.current=setSearchParams in the body of the hook to replace the useEffect @maastrich?

  12. maastrich commented on Jun 15, 2023

    @maastrich
  13. 15 remaining items

  14. bdwain commented on Aug 21, 2024

    @bdwain

    ah i see. mine doesn't work with multiple params as the previous state only knows the the current params the last time that specific piece of state changed

    any downside to doing this instead? I prefer it because it doesn't rely on a ref to pass the previous state to the setter function

    You can download the project, make your modification, and try running the unit tests against it. It's been a minute - but if I recall correctly, setSearchParams allows you to perform partial updates to the parameters. IE, you don't need to pass all of the search params every time. Thus it is necessary to maintain a reference to the old search params in order to build the new search params - only overwriting the supplied values.

  15. bdwain commented on Aug 21, 2024

    @bdwain

    @buzinas i had an issue with this version of the method when i made 2 changes to the url in quick succession in different hooks. They both acted off the same previous state.

    The example where this occurred is having a perPage and offset value on a paginated page, and changing the perPage value causes offset to reset back to 0.

    My solution was to move the reading of the current query variables as close as possible to the setting of the new ones, such that it's all synchronous, rather than trying to integrate it with the react lifecycle. This removes the option to pass the previous state to the setter, and requires you to pull document.location.search directly instead.

    export function useSearchParams() {
      const location = useLocation();
      const navigate = useNavigate();
    
      const searchParams = useMemo(
        () => new URLSearchParams(location.search),
        [location.search],
      );
    
      const setSearchParams = useCallback(
        (getNewParams: () => URLSearchParams) => {
          navigate(`?${getNewParams()}`);
        },
        [navigate],
      );
    
      return [searchParams, setSearchParams] as const;
    
    //example usage of setSearchParams
    setSearchParams(() => {
      const searchParams = new URLSearchParams(document.location.search);
      searchParams.set('foo', 'bar');
      return searchParams;
    });
  16. craigmiller160 commented on Mar 29, 2025

    @craigmiller160

    Please for the love of God fix this! Wtf who thought this was a good idea? This is a truly horrible regression and makes using react router more difficult.

  17. kentcdodds commented on Mar 29, 2025

    @kentcdodds
    MemberAuthor

    @craigmiller160 that attitude is unhelpful and unappreciated. If you feel so strongly, make a pull request.

  18. rwilliams3088 commented on Apr 18, 2025

    @rwilliams3088

    @craigmiller160 that attitude is unhelpful and unappreciated. If you feel so strongly, make a pull request.

    For the record, Pull Requests have been made and the react-router team has ignored them for over a year (maybe closer to 2 years now). No comments to improve or change anything. So @craigmiller160's exasperation, like all of ours, is justified.

  19. jon-frankel commented on May 3, 2025

    @jon-frankel

    This workaround worked for me. Based on this SO answer.

    function usePrevious(value: unknown) {
      const ref = useRef<unknown>();
      useEffect(() => {
        ref.current = value;
      }, [value]);
      return ref.current;
    }
    
    function useHasChanged(value: unknown) {
      const prevVal = usePrevious(value);
      return prevVal !== value;
    }
    
    function MyComponent({val, otherVal}) {
      const valHasChanged = useHasChanged(val);
      const [_searchParams, setSearchParams] = useSearchParams();
    
      useEffect(() => {
        if (!valHasChanged) {
          return;
        }
    
        setSearchParams(new URLSearchParams(`val=${val}&otherVal=${otherVal}`));
      }, [setSearchParams, val, otherVal, valHasChanged]);
    
      return <>...</>;
    }
  20. added a commit that references this issue on Feb 8, 2026
    9c2eef5
  21. added a commit that references this issue on Feb 15, 2026
    d035496
  22. greedyivan commented on Aug 25, 2026

    @greedyivan

    I went through this thread, the earlier PRs, and the redirect to useEffectEvent — and there is one fact that decides the shape of the fix, so I'll put it first.

    The shipped useEffectEvent does not have a stable identity. That is not an implementation detail — it is the contract: the React docs say its identity "intentionally changes on every render", and that effect events are only to be called from inside effects — not returned from hooks, not called from event handlers. setSearchParams is exactly both of those things. So setSearchParams = useEffectEvent(...) doesn't fix this issue — it churns harder than the current code (a new function every render, instead of every navigation).

    What the redirect is pointing at is the timing. React's effect-event mechanism reads fresh values because its internal reference is switched during the commit, before layout effects run. That timing is the fix. The upcoming PR reproduces it with documented primitives: setSearchParams holds one identity for the lifetime of the hook, and a call — through any reference, captured before or after a navigation — reads searchParams and navigate from the latest committed render. Event handlers, timeouts, and passive effects always see the latest committed values.

    This is also the shape every comparable setter already ships: dispatch from react-redux, navigate from TanStack Router, refetch from TanStack Query — stable reference, current state read at call time.

    Two things relative to #14785 (which I appreciate — it's what surfaced the redirect): its mirror switches in a passive effect, so there is a window where a captured reference still reads the previous navigation; and its callback keeps [navigate] in the deps, which churns on pathname changes outside data routers — so the reference isn't stable there. Both are covered: pathname navigations keep the identity, and functional updates read committed values.

    One boundary is real and documented rather than hidden: a call made from another component's useLayoutEffect that flushes earlier in the same commit may see the previous render's values. The platform mechanism has the same boundary — its switch also happens in the commit phase. And the existing queueing caveat stays true: two calls in the same tick don't build on each other; this is a URL setter, not React state.

    Nine new tests, six of them fail on current main. PR in a moment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions