Here is a complete, SEO-optimized article for:
๐งญ React Redirects & 404 Error Handling โ Navigate Smartly in React Router (2025)
๐งฒ Introduction โ Why Redirects and 404s Are Critical
Every React.js application needs to handle:
- ๐ Redirects after login, logout, or form submission
- ๐ซ 404 pages when users visit undefined routes
React Router (v6+) offers clean, declarative tools like <Navigate /> and wildcard routes (*) to manage redirects and error handling efficiently without page reloads.
๐ฏ In this guide, youโll learn:
- How to create redirects in React
- Navigate programmatically with
useNavigate() - Set up 404 Not Found pages
- Best practices for route fallback and access control
๐ 1. Redirect Using <Navigate />
<Navigate /> is a component that redirects users declaratively to another route.
โ Example:
import { Navigate } from 'react-router-dom';
<Route path="/home" element={<Navigate to="/" />} />
โ
Automatically redirects /home to /
โ๏ธ 2. Programmatic Redirect with useNavigate()
Use useNavigate() to redirect after logic like login, form submission, or logout.
import { useNavigate } from 'react-router-dom';
function Login() {
const navigate = useNavigate();
const handleLogin = () => {
// simulate auth logic
navigate('/dashboard');
};
return <button onClick={handleLogin}>Login</button>;
}
๐ Supports navigation with optional replace or state.
๐ฆ 3. Replace vs Push Redirects
navigate('/dashboard', { replace: true }); // replaces history
navigate('/dashboard'); // pushes new entry
Use Case:
replace: truefor redirects (e.g., login)- Push (default) for user-triggered navigation
๐ซ 4. 404 Not Found Page (Wildcard Route)
Use the path * to catch all undefined routes.
โ Example:
import NotFound from './pages/NotFound';
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>
โ
NotFound.jsx Component:
function NotFound() {
return (
<div>
<h1>404 โ Page Not Found</h1>
<p>The page you are looking for does not exist.</p>
</div>
);
}
โ Wildcard matches all unknown URLs and shows a fallback UI
๐ 5. Redirect Unauthorized Users
Protect routes using conditional <Navigate /> logic.
<Route
path="/admin"
element={isLoggedIn ? <AdminPanel /> : <Navigate to="/login" replace />}
/>
๐ Prevents unauthenticated access and replaces history to avoid back-button bypass
๐ 6. Redirect After Form Submit
const handleSubmit = () => {
// save data
navigate('/thank-you', { state: { from: 'contact' } });
};
In the ThankYou component:
const location = useLocation();
console.log(location.state?.from); // 'contact'
โ
Pass context between redirects using navigate() with state
๐ง 7. Summary of Redirect Methods
| Method | Use Case |
|---|---|
<Navigate to="/route" /> | Static, inline redirects |
useNavigate() | Redirect based on logic/events |
navigate(..., { replace }) | Prevent back-button after redirect |
Wildcard route (*) | Handle unknown paths with 404 page |
๐ Best Practices
โ
Use <Navigate /> for JSX-based, declarative redirects
โ
Use useNavigate() for logic-based programmatic navigation
โ
Always include a wildcard route for 404s
โ
Redirect on login/logout with { replace: true }
โ
Keep NotFound and redirect logic in a central route file
๐ Summary โ Recap & Next Steps
React Router provides simple yet powerful tools for handling redirects and 404 errors. With <Navigate />, useNavigate(), and path="*", you can guide users smoothly and securely through your app.
๐ Key Takeaways:
- Use
<Navigate />to redirect from one route to another - Use
useNavigate()to redirect after user actions - Always handle unknown routes with a custom 404 component
- Use
replace: truefor auth-related redirects
โ๏ธ Real-World Relevance:
From login flows to error pages, redirect handling ensures smooth UX in apps like Stripe, Auth0, and SaaS dashboards.
โ FAQ Section
โ How do I redirect a user after login in React?
โ
Use useNavigate() in your login handler:
navigate('/dashboard', { replace: true });
โ What’s the difference between <Navigate /> and useNavigate()?
โ
<Navigate /> is declarative and used inside JSX.
โ
useNavigate() is used programmatically inside component logic.
โ How do I handle a 404 in React Router?
โ
Add a wildcard route (*) at the end of your route list:
<Route path="*" element={<NotFound />} />
โ Can I pass state when redirecting?
โ
Yes. Use:
navigate('/success', { state: { orderId: 123 } });
Then access with useLocation().
โ Should I use replace: true on every redirect?
โ Only for authentication or final redirects.
โ
Keep browser history for navigable pages like /settings.
Share Now :
