Skip to content

useSearchParams no longer passes pending updates to multiple calls of setSearchParams function callback #14077

@mkartchner994

Description

@mkartchner994

Reproduction

https://codesandbox.io/p/devbox/nervous-albattani-wmmls2

If you type in the search box, only the page param gets added to the url. Once downgraded to v7.6.3, the search param also gets added to the url.

System Info

React Router >=v7.7.0

Used Package Manager

npm

Expected Behavior

The function callback no longer passes the pending URLSearchParams to the next setSearchParams call if they happened one after another. For instance:

function useFilter() {
  const [searchParams, setSearchParams] = useSearchParams();

  const resetPage = useCallback(() => {
    setSearchParams((params) => {
      params.set("page", "1");
      return params;
    });
  }, [setSearchParams]);

  const updateSearch = useCallback((value) => {
    setSearchParams((params) => {
      params.set("search", value);
      return params;
    });
    // -------- This resetPage call will end up overriding setting search
    // because the next function callback no longer gets the
    // pending params from the last function callback above.
    // This worked prior to v7.7.0
    resetPage();
  }, [resetPage, setSearchParams]);

  return {
    updateSearch,
    resetPage,
  };
}

This example is a little contrived but we have some complex filtering logic that uses similar patterns.

Actual Behavior

The pending updates are not passed to the next setSearchParams call so previous calls get overridden with whatever is called last.

The react-router documentations says setSearchParams "also supports a function callback like React's setState". And React's setState function callback does work in this way where multiple callback calls get put in a queue and then called in the same order to calculate the final state.

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