How to get and set URL params in React application

If you need to access the URL parameters inside your React application, without using any external libraries such as React Router, then read on.

URL or Query Params

URL parameters, also known as query parameters, are the key value pairs that are set as part of the URL. For example, in the URL https://example.com?foo=bar&zoo=car the variables foo and zoo are the parameters and bar and car are their respective values.

Reading URL Params

We can use the built-in URL object to access the URL params in our react application.

// https://example.com?foo=bar&zoo=car&moo
useEffect(() => {
    const url = new URL(document.location);
    const params = url.searchParams;
    console.log(params.get("foo")); // prints "bar"
    console.log(params.get("zoo")); // prints "car"
    console.log(params.get("moo")); // prints ""
    console.log(params.get("random")); // prints null
  }, []);

In the above code, we construct a new URL object by passing the current document's location. Then by using the searchParams property, we can access the query parameters. If any value is set for the given parameters, then a String representation of the value is returned. If no value is set, but the parameter is present in the URL, then an empty string is returned. If no parameters is found in the URL, then null is returned.

Reading an array of values from URL params

When you set multiple values under a same name, then you can read them as an array. To do this, instead of get method, use getAll then you will get back an array.

// https://example.com?foo=bar&foo=car&moo
  useEffect(() => {
    const url = new URL(document.location);
    const params = url.searchParams;
    console.log(params.getAll("foo")); // prints ['bar', 'car']
  }, []);

Setting a URL param

You can use URLSearchParams interface to manipulate the URL parameter values and then use it to set the new values in the current URL. For example:

const sp = new URLSearchParams(document.location.search);
  sp.set(keyName, 'newValue');
  document.location.search = sp;

This will cause a page reload and when it reloads, the new page will have the URL param set.

Creating a reusable React hook to read URL parameter

Let's extract these reading and updating query param logic as simple React hook, so it can be reused.

import { useEffect, useState } from "react";

function useQueryParam(keyName) {
  const [value, setValue] = useState();
  useEffect(() => {
    const url = new URL(document.location);
    const params = url.searchParams;
    setValue(params.get(keyName));
  }, []);
  const setParamValue = (newValue) => {
    const sp = new URLSearchParams(document.location.search);
    sp.set(keyName, newValue);
    document.location.search = sp;
  };
  return [value, setParamValue];
}

And, here's how you will use the newly created React hook.

import { useEffect, useState } from "react";
  export default function App() {
      const [foo, setFoo] = useQueryParam("foo");
      const [zoo] = useQueryParam("zoo");

      const handleClick = () => {
        setFoo(new Date().getTime());
      };

      return (
        <div className="App">
          <h1>Query Params: {foo} {zoo}</h1>
          <button onClick={handleClick}>Set</button>
        </div>
      );
}