3 Ways to Get Query Params in React (Without Router Too)

Ferenc Almasi β€’ 2022 September 09 β€’ πŸ“– 2 min read

To get query params in React without using React Router, we can use the URLSearchParams API. Take the following URL as an example:

webtips.dev?tutorial=react

In order to get the value of the query param from the above URL, let's create a new URLSearchParams object and use its get method with the name of the query param:

const Component = () => {
    const searchParams = new URLSearchParams(document.location.search)

    return (
        <div>Tutorial: {searchParams.get('tutorial')}</div>
    )
}
Using URLSearchParams to get query params
Copied to clipboard!

You will need to pass the name of the query param as a string to the get method to retrieve its value. You can do this with as many parameters as needed. Make sure you pass document.location.search to the URLSearchParams call in order to get the right query params.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
JavaScript Course

With React Router v6

If you are using the latest version of React Router, it has a built-in useSearchParams hook that we can use to get query parameters. You can use the hook in the following way:

import { useSearchParams } from 'react-router-dom'

const Component = () => {
    const [searchParams, setSearchParams] = useSearchParams()

    return (
        <div>Tutorial: {searchParams.get('tutorial')}</div>
    )
}
Make sure you useΒ useSearchParams inside a router
Copied to clipboard!

You can also use this hook to set query parameters with the second setSearchParams function.


With React Router v5

If you are still using a lower version of React Router than v6, then you will need to use the useLocation hook in combination with the URLSearchParams API, similar to the first example:

import { useLocation } from 'react-router-dom'

const Component = () => {
    const search = useLocation().search
    const searchParams = new URLSearchParams(search)

    return (
        <div>Tutorial: {searchParams.get('tutorial')}</div>
    )
}
Getting query params using useLocation
Copied to clipboard!
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in 5 hours.

Learn More

πŸ“š Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. β˜•

Get access Support us
Read more on
πŸŽ‰ Thank you for subscribing to our newsletter. x