Check your version
This post assumes you're using React Router v6. If not, find your version below.

If you’ve ever jammed with the console cowboys in cyberspace, you’ve almost certainly run into query strings before. They’re the ? and & you see appended onto URLs.

Query String Example
twitter.com/search?q=ui.dev&src=typed_query&f=live

They’re a fundamental aspect of how the Web works as they allow you to pass state via the URL. Above is an example of a query string you’d see if you searched for ui.dev on Twitter.

The query portion of this URL has three keys, q, src, and f. q represents the text we type into Twitter’s search bar, src tells Twitter how we did it (via typing into the search bar), and f filters the results of the query by “Latest”.

What’s nice about this is it’s sharable. You could copy and paste that URL into your browser right now and it would work. All the data Twitter needs to properly render the UI is right there in the URL.

With all that said, odds are you’re not here to learn what query strings are but instead how to use them with React Router. The good news is that if you’re already comfortable with React Router, there are just a few small details you need to know.

Let’s say we were Twitter and we were building the Route for the URL above. It would probably look something like this.

<Route path='/search' element={<Results />} />

Notice at this point there’s nothing new. We don’t account for the query string when we create the Route. Instead, we get and parse it inside the component that is being rendered when that path matches - in this case, Results.

Now the question becomes, how do we actually do this? Before we can answer that question, we first need to learn about the URLSearchParams API.


URLSearchParams

The URLSearchParams API is built into all browsers (except for IE) and gives you utility methods for dealing with query strings.

When you create a new instance of `URLSearchParams`, you pass it a query string and what you get back is on object with a bunch of methods for working with that query string.

Take our Twitter query string for example,

const queryString = "?q=ui.dev&src=typed_query&f=live";
const sp = new URLSearchParams(queryString);
sp.has("q"); // true
sp.get("q"); // ui.dev
sp.getAll("src"); // ["typed_query"]
sp.get("nope"); // null
sp.append("sort", "ascending");
sp.toString(); // "?q=ui.dev&src=typed_query&f=live&sort=ascending"
sp.set("q", "bytes.dev");
sp.toString(); // "?q=bytes.dev&src=typed_query&f=live&sort=ascending"
sp.delete("sort");
sp.toString(); // "?q=bytes.dev&src=typed_query&f=live"

useSearchParams

As of v6, React Router comes with a custom useSearchParams Hook which is a small wrapper over the browser’s URLSearchParams API.

useSearchParams returns an array with the first element being an instance of URLSearchParams (with all the properties we saw above) and the second element being a way to update the query string.

Going back to our example, here’s how we would get the values from our query string using useSearchParams.

import { useSearchParams } from 'react-router-dom'
const Results = () => {
const [searchParams, setSearchParams] = useSearchParams();
const q = searchParams.get('q')
const src = searchParams.get('src')
const f = searchParams.get('f')
return (
...
)
}

Then if we needed to update the query string, we could use setSearchParams, passing it an object whose key/value pair will be added to the url as &key=value.

import { useSearchParams } from 'react-router-dom'
const Results = () => {
const [searchParams, setSearchParams] = useSearchParams();
const q = searchParams.get('q')
const src = searchParams.get('src')
const f = searchParams.get('f')
const updateOrder = (sort) => {
setSearchParams({ sort })
}
return (
...
)
}
Want to learn more?
If you liked this post and want to learn more, check out our free Comprehensive Guide to React Router.

Before you leave

I know, "another newsletter pitch" - but hear me out. Most JavaScript newsletters are terrible. When's the last time you actually looked forward to getting one? Even worse, when's the last time you actually read one rather than just skim it?

We wanted to change that, which is why we created Bytes. The goal was to create a JavaScript newsletter that was both educational and entertaining. 84,226 subscribers and an almost 50% weekly open rate later, it looks like we did it.

Delivered to 84,226 developers every Monday

Avatar for Tyler McGinnis

Tyler McGinnis

CEO of ui.dev. Obsessed with teaching, writing, swimming, biking, and running.

Share this post

Want more react-router?

This is part of our React Router course. You can take the rest of the course by starting a free 3-day trial.