Did react useSearchParams hook will unmount component?

Viewed 47

I have this code in component:

const [searchParams, setSearchParams] = useSearchParams()
searchParams.set('page', '1')

When it run, other components state value is clear up, so I think setSearchParams not re-render component, it's reload component.

Is what I think right?

1 Answers

I don't think you've got it right. The searchParams object is only an object representing the current URL queryString parameters. Updating it alone has no action or effect on anything unless you then call setSearchParams with the updated searchParams object.

The setSearchParams is similar to the navigate function in that it dispatches a navigation action but is only setting the URL's queryString parameter.

The setSearchParams function only takes up to two arguments, the first the searchParams object you want to update the URL queryString value to be and the second is the navigation options.

useSearchParams

declare function useSearchParams(
  defaultInit?: URLSearchParamsInit
): [URLSearchParams, SetURLSearchParams];

type ParamKeyValuePair = [string, string];

type URLSearchParamsInit =
  | string
  | ParamKeyValuePair[]
  | Record<string, string | string[]>
  | URLSearchParams;

type SetURLSearchParams = (
  nextInit?: URLSearchParamsInit,
  navigateOpts?: : { replace?: boolean; state?: any }
) => void;

If all you've done is mutated the searchParams object there will be no side-effects like resetting or remounting any other external React components. It won't rerender or remount the component using the useSearchParams hook either.

Related