Last updated: Apr 7, 2024
Reading timeยท2 min
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')
.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.
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 setSearchParams
function works like the navigate
function from the
useNavigate hook, but only
for the search portion of the URL.
const removeQueryParams = () => { const param = searchParams.get('q'); if (param) { // ๐๏ธ Delete each query param searchParams.delete('q'); // ๐๏ธ Update state after setSearchParams(searchParams); } };
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 parameters of the route.
If you need to update the query parameters using React Router, click on the link and follow the instructions.