Borislav Hadzhiev
Sun Apr 24 2022·2 min read
Photo by Jason An
To remove query params using React router:
useSearchParams
hook to get the current location's search params.delete()
method to delete each query param, e.g.
searchParams.delete('q')
.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: 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> ); }
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 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.
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.