How to remove query params using React router


Borislav Hadzhiev

Last updated: Apr 24, 2022


Photo from Unsplash

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, e.g. setSearchParams(searchParams).
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:}); }; 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

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

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.

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 params of the route.

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.