Use Cases



Developer How-Tos

How to use URLSearchParams and React Router to easily handle URL query parameters

The web apps of today handle very large datasets, some so large that users can’t make use of them without a way to reduce the dataset or reorganize them in a meaningful way. To achieve this, we typically provide users with ways to search, filter, and sort through the data. This can be seen in web stores, where a user can search for specific products in a store, or social media platforms, where a user can filter out the posts of only their closest friends and sort them by the number of likes they have. These features are essential to the user's experience.

A good practice is to track a user's search, filter, and sort actions within the URL as query parameters so they can not only persist upon a page refresh but can also be shared with other users. For instance, a user searching for cat videos should produce a https://example.com/videos?=Cats URL that when navigated to would automatically search the web app’s dataset for ‘Cats’.

Query parameters are nothing new and websites that are server-side rendered make use of them extensively. But in the age of client-side rendered web applications, they tend to be overlooked since query parameters are not required to request filtered data to the server. 

The reason they tend to be overlooked is that they can be a pain to manage. This is often because a ‘query string,’ as the name implies, is a string and not a well-defined data structure, so manipulating it is a challenge, especially when dealing with various parameters across a large application.

This is where URLSearchParams comes to the rescue.

URLSeachParams is a relatively recent Web API that is supported by all browsers except IE. This API provides us with a solid data structure with utility methods to work with query strings in a more streamlined manner.

  1. Create a new URLSearchParams object

To create a new URLSearchParams object you use the constructor.

const params = new URLSearchParams()

Now you can start using the append utility method ‘append’ to start adding parameters.

params.append('name', 'John')
params.append('age', '32')

You can also pass in an existing query string or object when creating the URLSearchParams object and get the same result.

const params = new URLSearchParams(‘?name=Jogn&age=32’)

const params = new URLSearchParams({name: ‘John’, age: 32})

  1. Place URLSearchParams into your URL

So far we have only learned how to use URLSearchParams to store and manage our query parameters, but how do we actually put them in our URL?

That's where React Router comes in. React Router is one of the most popular libraries for handling routing in react applications and comes with many utilities to manipulate the URL in a react-friendly way.

 The main utility we will be using is the React Router history object. 

pathname: '/people',
search: params.toString() // '?name=John&age=32

With history, we can use its push method to navigate to a new path(pathname) and include any search parameters(search). In order to use our URLSearchParams here, we must utilize the toString method which constructs our query string by adding the ‘?’ delimiter and joins the parameters with an ampersand ‘&’.

Now we know how to use URLSearchParams in conjunction with react-router to easily manage query parameters and add them to the URL. 

  1. Simplify your interface

Now let’s create a hook that can abstract away everything we did above and provide an even simpler interface to add query parameters.

import { useMemo } from "react";
import { useLocation, useHistory } from "react-router-dom";
export const useParams = () => {
  const history = useHistory();
  const location = useLocation();

  // Creates a URLSearchParams object given any existing query string that is on the url
  const params = new URLSearchParams(location.search);

  // Function that gets called by any component that wants to update the URL parameters
  const setParams = (name, vale) => {

    // Sets new parameters onto our URLSearchParams object
    params.set(name, val);

    // Pushes new parameters onto the current URL using URLSearchParams object toString method
      pathname: location.pathname,
      search: params.toString(),

// Return the URLSearchParams object so components can read current URL parameters and the setParams function so components can modify URL parameters.
return [params, setParams];

The hook can be further expanded on to allow for bulk parameter additions and deletions or can be modified to only change the URL and not add it to the history stack. That will depend on your specific needs, but I hope this serves as a good starting point to easily handle URL query parameters.

By Andres Galindo

Related Articles

Subscribe to the zestiest newsletter in the industry

Get the latest from the Zesty team, from whitepapers to product updates.