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

Ferenc Almasi β€’ Last updated 2023 March 17 β€’ Read time 2 min read
  • twitter
  • facebook
React

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:

Copied to clipboard! Playground
const Component = () => {
    const searchParams = new URLSearchParams(document.location.search)

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

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.


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:

Copied to clipboard! Playground
import { useSearchParams } from 'react-router-dom'

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

    return (
        <div>Tutorial: {searchParams.get('tutorial')}</div>
    )
}
Make sure you use&nbsp;useSearchParams inside a router

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:

Copied to clipboard! Playground
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
  • twitter
  • facebook
React
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.