๐Ÿงญ React Routing
Estimated reading: 4 minutes 58 views

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: true for 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

MethodUse 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: true for 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿงญ React Redirects & 404 Error Handling

Or Copy Link

CONTENTS
Scroll to Top