How to Get Query Params in React (Easy Methods)

how to get query params in react

Working with query parameters is essential for passing data through URLs in modern web applications. Whether you’re building a search page, handling user inputs through URL state, or managing pagination, React developers frequently need to access query parameters. Understanding how to get query params in React can help improve your app’s functionality and make your user interactions smoother.

In this article, we’ll explore several ways to fetch query parameters in React—from using built-in JavaScript tools like URLSearchParams to leveraging modern libraries like React Router. Let’s dive in and explore how to integrate query params seamlessly.


What Are Query Params in React?

In React, query parameters (query params) are key-value pairs appended to the end of a URL. They provide additional information to the app without altering the route or page. For example:
https://example.com/search?query=React&sort=desc

Here, query and sort are query parameters that allow the app to customize content based on user input.


Benefits of Using Query Parameters

Query parameters offer several advantages:

  • State persistence: Values stay in the URL, so refreshing the page doesn’t lose state.
  • Deep linking: Users can share specific app states directly via links.
  • SEO-friendly structure: Allows search engines to index different states efficiently.
  • User convenience: Makes it easy to bookmark pages with applied filters or searches.

Basic Structure of Query Parameters

Query parameters are always attached to the URL after a ? and consist of key-value pairs. Multiple parameters are separated by an ampersand (&).

Example:
https://example.com/products?category=shoes&color=black

  • category = shoes
  • color = black

Prerequisites for Fetching Query Params in React

Before diving into the code, ensure you have:

  • A React project set up with create-react-app or another build tool.
  • React Router (if you’re using it for routing). Install it using:
    bash
    npm install react-router-dom

Getting Query Params in React Using URLSearchParams

One of the simplest ways to fetch query parameters in React is by using JavaScript’s native URLSearchParams object.

javascript
import { useEffect } from 'react';

const SearchPage = () => {
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const query = params.get('query');
console.log('Search Query:', query);
}, []);

return <h1>Search Page</h1>;
};

export default SearchPage;

Explanation:

  • The URLSearchParams object extracts parameters from the window.location.search string.
  • params.get('query') fetches the value of the query parameter.

React Router v5: How to Get Query Params

If you’re using React Router v5, you can access query params from the location prop.

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

const SearchPage = () => {
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const query = queryParams.get('query');

return <h1>Search Result for: {query}</h1>;
};


React Router v6: Accessing Query Params

With React Router v6, the method to access query parameters has shifted slightly. You now leverage the useSearchParams hook.

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

const SearchPage = () => {
const [searchParams] = useSearchParams();
const query = searchParams.get('query');

return <h1>Search Result for: {query}</h1>;
};


How to Handle Multiple Query Parameters in React

Managing multiple parameters becomes straightforward with URLSearchParams.

javascript
const category = searchParams.get('category');
const color = searchParams.get('color');

Updating Query Params Without Reloading

To update query parameters without reloading the page, manipulate the browser history.

javascript
import { useNavigate } from 'react-router-dom';

const FilterPage = () => {
const navigate = useNavigate();

const updateQuery = () => {
navigate('?category=shoes&color=black', { replace: true });
};

return <button onClick={updateQuery}>Apply Filter</button>;
};


How to Use Query Params with Forms in React

Using query params with forms allows users to preserve their input after submission.

javascript
const handleSubmit = (e) => {
e.preventDefault();
navigate(`?query=${inputValue}`);
};

FAQs

1. How do I get query params in React Router v6?

Ans – Use the useSearchParams hook for React Router v6.

2. What’s the difference between path params and query params?

Ans – Path params are part of the route, while query params come after the ? in URLs.

3. Can I use query params with dynamic routes?

Ans – Yes, query parameters work independently of dynamic routes.

4. How do I remove query params in React?

Ans – Use the replace option with navigate() to remove parameters.

5. Is URLSearchParams supported in all browsers?

Ans – Yes, it’s widely supported in modern browsers.

6. Can query parameters affect SEO?

Ans – Yes, poorly managed parameters can result in duplicate content issues.


Conclusion

Handling query parameters effectively is crucial for modern React applications. From implementing filters to managing pagination, learning how to get query params in React allows developers to build dynamic and user-friendly apps.

Whether you choose the native URLSearchParams method or React Router hooks, mastering query params will significantly enhance your app’s capabilities.

Was this article helpful?
YesNo
Scroll to Top