How to remove query params using React router

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# Remove query params using React router

To remove query params using React router:

  1. Use the useSearchParams hook to get the current location's search params.
  2. Use the delete() method to delete each query param, e.g. searchParams.delete('q').
  3. Update the search parameters.
App.js
import {useSearchParams} from 'react-router-dom'; export default function App() { const [searchParams, setSearchParams] = useSearchParams(); const removeQueryParams = () => { const param = searchParams.get('q'); if (param) { // ๐Ÿ‘‡๏ธ Delete each query param searchParams.delete('q'); // ๐Ÿ‘‡๏ธ Update state after setSearchParams(searchParams); } }; const handleChange = event => { setSearchParams({q: event.target.value}); }; console.log(searchParams.get('q')); return ( <div> <button onClick={removeQueryParams}>Remove query param</button> <input id="search" autoComplete="off" onChange={handleChange} /> </div> ); }

remove query param

The code for this article is available on GitHub

We can use the useSearchParams hook to manage query parameters in React router v6 and onwards.

App.js
const [searchParams, setSearchParams] = useSearchParams();

The hook is used to read and modify the query string in the URL for the current location.

It returns an array containing 2 elements - const [searchParams, setSearchParams] = useSearchParams().

The first element is an object that we can use the get the value of a query parameter and the second is a function that takes an object of key-value pairs to which it sets the query params.

The setSearchParams function works like the navigate function from the useNavigate hook, but only for the search portion of the URL.

App.js
const removeQueryParams = () => { const param = searchParams.get('q'); if (param) { // ๐Ÿ‘‡๏ธ Delete each query param searchParams.delete('q'); // ๐Ÿ‘‡๏ธ Update state after setSearchParams(searchParams); } };
The code for this article is available on GitHub

We have to use the URLSearchParams.delete() method to delete each query parameter.

Note that it's not enough to just delete the query parameters. We have to call the setSearchParams method, e.g. setSearchParams(searchParams) after we have deleted the query params.

The setSearchParams method that we got back from the useSearchParams hook is used to update the query parameters of the route.

If you need to update the query parameters using React Router, click on the link and follow the instructions.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev