React Custom Hook: UseQueryParams

React Custom Hook: UseQueryParams

Custom React Hooks

ยท

3 min read

Note: This article assumes you already know how to use React Hooks. If you want to get up to speed on React hooks please take a look at the reactJS docs here

Some Background

Query strings are commonplace when we use or create web applications and they are an effective way of parsing data to your pages without explicitly declaring them in your routes. Recently I was looking for a way to search query parameters from a URL that looks similar to this http://localhost:3000/app/dashboard/artist?artistId=90&name=Yoram. I discovered that Javascript already has a solution to this with the URLSearchParams API that does search and create query strings for you.

This is the API we are going to base our custom hook on so we can utilise it in many other components in our application

For more Information about the URLSearchParams and its utility methods visit the Link below

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

Hook Implementation

We will utilize the URLSearchParams Utility methods and the useLoaction method from react-router-dom to provide us with the URL.

import { useLocation } from "react-router-dom";

export function useQueryParams() {
  const query = new URLSearchParams(useLocation().search);
  return query;
}

How to use the Hook

Let's take this URL as an example http://localhost:3000/app/dashboard/artist?artistId=90&name=Yoram. What we want is to get the artist ID or name from this URL.

import React, { FunctionComponent} from "react";

import { useQueryParams } from "~/utils/hooks/useQueryParams";

export const Artist: FunctionComponent = () => {
  const query = useQueryParams();
  const artistId = query.get("artistId");  //90
}

Note: get() is not the only method you can use from this API click here to you provide more methods to utilise the full potential of this hook.


Share ๐Ÿ’›

Do you like this article? Do you want to support me? Share this article with your friends. Thank you!

Questions and Feedback

You got any questions or want to add your thoughts? Let me know in the comments below, please.