Skip to content

Instantly share code, notes, and snippets.

@max10rogerio
Created August 31, 2021 01:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max10rogerio/585ea597271c844a29657d00fc4d9bd8 to your computer and use it in GitHub Desktop.
Save max10rogerio/585ea597271c844a29657d00fc4d9bd8 to your computer and use it in GitHub Desktop.
useQuery Hook - React with react-router-dom - TS
import { useLocation } from "react-router-dom";
/**
* Get URL query params as object
*
* Example:
*
* ```tsx
* type Query = {
* q: string
* }
*
* const MyComponent = () => {
* const { q } = useQuery<Query>();
*
* return (
* <h1>{q}</h1>
* );
* }
* ```
*/
export const useQuery = <T = Record<string, any>>(): Partial<T> => {
const location = useLocation();
const urlSearchParams = new URLSearchParams(location.search);
const queryParams = Object.fromEntries(urlSearchParams);
return queryParams as any;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment