How to Get Query String Values in React Using JavaScript

Published on Dec 1, 2021
~5 min read
JSX
// Utility helper for getting query string values
const useQueryParam = (query) => {
const { search } = window.location;
const searchParameters = new URLSearchParams(search);
return searchParameters.get(query);
};
export default useQueryParam;

Logic

Web pages allow requests to be made with a query string.

It usually looks something like this:

https://website.com/subscribe?coupon=15off

In the example above there is one query parameter, named coupon and it has the value 15off.

You can have more than one query parameter, it would look something like the below:

https://website.com/subscribe?coupon=15off&student=no

So now the query paramters are coupon & student with the values 15off and no.

Sometimes you will need to access the values of a query inside the browser, so that you can send them as part of response. You can do that using JavaScript, and the URLSearchParam API.

Because this is a frequently used function, we can create a hook to reduce duplication and to create better composition rather than using the below JavaScript each time we need to query a parameter.

JS
const params = new URLSearchParams(window.location.search);

Explaination

This is a simple hook that takes query as an argument and then extracts the value. Here's how it gets the query string value in JavaScript.

First it deconstructs the search property of the Location interface, with:

JS
const { search } = window.location;

To use it we:

JS
const searchParameters = new URLSearchParams(search);

The above will return the query string, that is all the text following the ?. So using an earlier example like:

https://website.com/subscribe?coupon=15off

URLSearchParams(search) will give use the string ?coupon=15off.

Now that it has extracted the params object, the hook will query and return it with:

JS
return searchParameters.get(query);

The final line of the hook is getting the value of the parameter so that it can be passed back to the response. So it will get 15off in this case.

Usage

Continuing with the coupon example we could then send it back as part of a price fetch request, to update the pricing information with the coupon applied.

Here's how it might be used:

JSX
import useQueryParam from "./useQueryParam";
const useSignUpData = () => {
const couponCode = useQueryParam("coupon");
return (
useSuspenseApi <
useSignUpData >
("useSignUpData",
() =>
fetchuseSignUpData({
couponCode,
}))
);
};
export default useSignUpData;

Vanilla JavaScript Implementation

If you were to convert this hook back to vanilla JS, we could do so like this:

JS
const queryParams = new URLSearchParams(window.location.search);

Now you have the params object, store in the queryParams variable you can begin to query it.

You get the value of the parameter with:

JS
queryParams.get("coupon");

You can also just check if a query parameter exists within the params object with:

JS
queryParams.has("coupon");

Other URLSearchParams Methods

The URLSearchParams API has lots of method the you could add to the hook. You would just need to pass the methods as optional parameters so you can use them adapt the hooks usability.

You can iterate over all of the parameters with:

JS
for (const param in queryParams) {
console.log(param);
}

If the query was:

https://website.com/subscribe?coupon=15off&student=no

Then it would log ['coupon', '15off'] and ['student'. 'no'].

This method is very useful if your query string for some reason has the same a parameter multiple times. For instance:

https://website.com/subscribe?coupon=15off&coupon=50off

If you were to call queryParams.get('coupon'), you would only get the first value back. This is because URLSearchParams doesn't automatically detect if a parameter value has been passed more than once. Making iteration useful.

However, there is also the getAll() method that gets back an array with all the values passed.

Other methods the URLSearchParams has for looping over the query parameters that you have probably seen in JavaScript are:

  • forEach() iterates through all values in query string object
  • keys() returns an iterator with all the keys of the query string object
  • values() returns an iterator with all the values of the query string object
  • enteries() with all the keys/value pairs of the query string object

There are many other useful methods that can be found here, methods that let you modify you query string like append() or delete().

The hook should be enough to get query string values in JavaScript with URLSearchParams.

Picture of author

Peter Lynch

Web Developer & Bootcamp grad who wants to learn as much as he can check me out on twitter.

Starting from the bottom newsletter

This newsletter is a record of my journey as an indie hacker, developer, entrepreneur, and human. Delivered straight to your inbox each Sunday.