You can use next/router
to remove the query params in the URL.
const router = useRouter();
router.replace('/about', undefined, { shallow: true });
Use replace
to prevent adding a new URL entry into the history (otherwise just use push
), and shallow: true
allows you to change the URL without running data fetching methods. This will cause a re-render but will not refresh the page per se.
The above solution will remove all query parameters from the URL. If you want to only remove a specific parameter you can use the code below instead.
const removeQueryParam = (param) => {
const { pathname, query } = router;
const params = new URLSearchParams(query);
params.delete(param);
router.replace(
{ pathname, query: params.toString() },
undefined,
{ shallow: true }
);
};
removeQueryParam('something');