React: useSearchParams Custom Hook (Router v5)

Date: 2023-04-17

Source: https://brianm.me/posts/react-router-search-params/

TL;DR

import { useLocation } from 'react-router-dom';
import { useMemo } from 'react';

interface ReadOnlyURLSearchParams extends URLSearchParams {
  append: never;
  set: never;
  delete: never;
  sort: never;
}

export function useSearchParams() {
  const { search } = useLocation();

  return useMemo(
    () => new URLSearchParams(search) as ReadOnlyURLSearchParams,
    [search]
  );
}
76790cookie-checkReact: useSearchParams Custom Hook (Router v5)