Skip to content

Instantly share code, notes, and snippets.

@kriskarpenko
Last active October 18, 2022 05:14
Show Gist options
  • Save kriskarpenko/c967413b6775854ac422dae7dafaefa4 to your computer and use it in GitHub Desktop.
Save kriskarpenko/c967413b6775854ac422dae7dafaefa4 to your computer and use it in GitHub Desktop.
useQueryParams hook for React Router v6
import { useSearchParams } from "react-router-dom";
/**
* Hook to get all query params as key value pairs.
* Usage:
* const {param1, param2} = useQueryParams()
* const queryParams = useQueryParams()
* @returns {} object with all query params as key value pairs
*/
export function useQueryParams() {
const [searchParams] = useSearchParams();
const result = {};
searchParams.forEach((value, key) => (result[key] = value));
return result;
}
@karpolan
Copy link

Nice, can you provide example of usage?

@karpolan
Copy link

This code is more clear

searchParams.forEach((value, key) => {
   result[key] = value
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment