Back to Code Bytes
2 min read
getQueryParam()

Description

getQueryParam instantiates a URLSearchParams object from window.location.search and returns the value for the given key, or null if the parameter is not present.

Code Byte

export const getQueryParam = (key: string): string | null  => {
  return new URLSearchParams(window.location.search).get(key);
}

Use cases:

  • Reading filters: Apply list filters (e.g., ?status=active) based on URL parameters.
  • Deep linking: Restore component state (e.g., open a modal) from URL params.
  • Analytics: Capture campaign or referral codes from the query string.
  • Form prefill: Populate form fields (e.g., search inputs) from URL parameters.

Example usage:

import { getQueryParam } from './get-query-param.util';

// 1) Capture 'ref' parameter for referral tracking
const referrer = getQueryParam('ref');
if (referrer) {
  console.log(`Referred by: ${referrer}`);
}

// 2) In a React component to initialize state
import { useState, useEffect } from 'react';

function SearchPage() {
  const [query, setQuery] = useState<string>(() => getQueryParam('q') ?? '');

  useEffect(() => {
    // Fetch results whenever 'q' param changes
    fetchResults(query);
  }, [query]);

  return (
    <input
      type="text"
      value={query}
      onChange={e => setQuery(e.target.value)}
      placeholder="Search..."
    />
  );
}