Query parameter hook (React)

Licensed under 0BSD. Use this code for any purpose. No attribution required. Use at your own risk.

import { useState } from 'react';

export function useQueryParameter(parameterName: string) {
  const [initialQueryParameter] = useState(() => {
    try {
      const searchParameters = new URLSearchParams(window.location.search);
      return searchParameters.get(parameterName) ?? undefined;
    } catch (e) {
      console.warn(`Could not read initial value for query parameter "${parameterName}". Error:`, e);
      return undefined;
    }
  });

  return {
    initialQueryParameter,
    changeQueryParameter: (newValue: string) => {
      try {
        const searchParameters = new URLSearchParams(window.location.search);
        searchParameters.set(parameterName, newValue);
        history.replaceState(null, '',
          window.location.pathname + '?' + searchParameters.toString()
        );
      } catch (e) {
        console.warn(`Could not set new value for query parameter "${parameterName}". Error:`, e);
      }
    },
  };
}