I'm using react router for routing in my app, and I can't seem to figure out how to use the useSearchParams hook in order to clear the search params upon navigating to a new route.
I've tried to utilize the cleanup function of useEffect in order to clean up the search params, but it seems to navigate to the previous route upon exiting the component.
The basic code is something like the following:
import * as React from "react";
import { Routes, Route, Outlet, Link, useSearchParams } from "react-router-dom";
export default function App() {
return (
<div>
<h1>Basic Example</h1>
<p>
Lorem ipsum
</p>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
<Route path="dashboard" element={<Dashboard />} />
<Route path="*" element={<NoMatch />} />
</Route>
</Routes>
</div>
);
}
function Layout() {
return (
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/dashboard">Dashboard</Link>
</li>
<li>
<Link to="/nothing-here">Nothing Here</Link>
</li>
</ul>
</nav>
<hr />
<Outlet />
</div>
);
}
function About() {
const [searchParams, setSearchParams] = useSearchParams();
useEffect(() => {
return () => {
searchParams.delete("someParam")
setSearchParams(searchParams); // This will route back to the `About` component
}
}, setSearchParams)
return (
<div>
<h2>About</h2>
</div>
);
}
And I made a demo.