Why the Page Reloads
A full page reload happens when the browser performs a normal navigation. In React apps, you want navigation to be handled client‑side so that the app’s state is preserved and only the relevant component re‑renders. The issue usually stems from a mismatch between the link path and the defined route, or from using a non‑React link element.
Matching Link to Route
Your header uses `<Link to="/allusers">` while the route is defined for `'/userlist'`. React Router will try to find a matching route and, if none exists, falls back to a normal browser navigation, causing a reload. Align the paths so the router can intercept the navigation.
// Header.js
import { Link } from "react-router-dom";
export default function Header() {
return <Link to="/userlist">All Users</Link>;
}
// App.js (React Router v6)
import { BrowserRouter, Routes, Route } from "react-router-dom";
import UsersList from "./user/UsersList";
function App() {
return (
<BrowserRouter>
<Header />
<Routes>
<Route path="/userlist" element={<UsersList />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Using Programmatic Navigation
When you need to redirect from code (e.g., after form submission), use the `useNavigate` hook. It returns a function that performs a client‑side push to the new route without reloading.
import { useNavigate } from "react-router-dom";
function SubmitButton() {
const navigate = useNavigate();
const handleClick = () => {
// perform actions
navigate("/userlist");
};
return <button onClick={handleClick}>Go to Users</button>;
}
Avoiding Full Reloads in Older Versions
If you’re on React Router v5, replace `Switch` with `Routes` and `component` with `element`. For v4, ensure you import `BrowserRouter` at the root and that your links use `Link` from `react-router-dom`. Any direct `<a href="...">` will trigger a reload.
Testing the Navigation
Open the app, click the link, and observe that the URL changes while the page content updates without a full refresh. Use the browser’s network tab to confirm no new document is fetched.
Takeaway: Align your `<Link>` paths with `<Route>` paths and use `useNavigate` for programmatic redirects to keep navigation client‑side.
People also ask
What if I need to pass state to the next page?
Use the `state` prop on `Link` or the second argument of `navigate`, e.g., `navigate('/userlist', { state: { from: 'header' } })`.
How do I keep the page from reloading on a form submit?
Prevent the default submit event (`e.preventDefault()`) and then use `navigate` to change routes.
Inspired by a public discussion on Stack Overflow. This article is an original explanation for learners.