Skip to main content

Query parameter

This hook reads the initial value of a query parameter and makes it available. It also offers a function to update the query parameter. When the query parameter is updated, this hook's returned value does not change. This is to avoid infinite loops in the application's state.

Usage​

my-component.tsx
function MyComponent() {
const { initialQueryParameter, changeQueryParameter } =
useQueryParameter('q');
const [query, setQuery] = useState(initialQueryParameter ?? '');

const onSearch = () => {
// Update the query parameter, so that users can copy and share the URL
changeQueryParameter(query);

performTheActualSearch(query);
};

return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<button onClick={onSearch}>Search</button>
</>
);
}

Source code​

use-query-parameter.tsx
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
);
}
},
};
}