React Hooks - How to get parameter value from query string

Viewed 30420

How can I use react hooks and get query string value?

with react class I use : const id = this.props.match.params.id;

4 Answers

here is another pure javascript way

assuming your URL = localhost:3000/example?id=123

  React.useEffect(() => {

    const params = new URLSearchParams(window.location.search) // id=123
    let id = params.get('id') // 123 

}, [])

you can also check if the query params exist or not by has like

params.has('id') // true
params.has('name') // false

In React Hooks:

Suppose your URL is like this: http://localhost:3000/user?name=John&id=10

Then you can use useLocation hook to get your job done.

import React from 'react';
import { useLocation } from "react-router-dom";

function VerifySignup() {
    const search = useLocation().search;
    const name = new URLSearchParams(search).get('name');
    const id = new URLSearchParams(search).get('id');
    console.log({ name, id })
    return (
        <div>
            Verify Signup
        </div>
    )
}

export default VerifySignup

You can use useParams and set the id as a dependency of the effect:

const Component = () => {
  const { id } = useParams();
  useEffect(() => 'do something when id changes', [id]);
};
Related