Skip to content

Instantly share code, notes, and snippets.

@eesa1980
Last active May 13, 2022 10:12
Show Gist options
  • Save eesa1980/1f21275b85840d8215b9c69f989ceada to your computer and use it in GitHub Desktop.
Save eesa1980/1f21275b85840d8215b9c69f989ceada to your computer and use it in GitHub Desktop.
A hook in react to return url params #React #CustomHook #URLSearchParams
/**
* A hook in react to return url params
*/
export const useUrlParams = () => {
const location = useLocation()
const [search] = useState<URLSearchParams>(
new URLSearchParams(location.search)
)
return useCallback(
<T extends unknown>(...param: string[]): T => {
const obj: Record<string, unknown> = {}
param.forEach((p: string) => {
if (p !== null) {
obj[p] = search.get(p)
}
})
return <T>obj
},
[search]
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment