#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Routing and Navigation

Redirecting the User

Redirecting means sending the user to a different route without them clicking a link: after a login succeeds, when they visit a page they are not allowed to see, or when an old URL has moved. In a React app using React Router, redirects happen in the browser, with no full page reload. React Router offers two tools: the <Navigate> component for redirects during rendering, and the useNavigate hook for redirects triggered by code such as an event handler.

Redirecting as part of rendering

When the decision depends on what the component would show, render <Navigate to="..." />. React Router performs the redirect as soon as it renders. This suits protected routes, where a logged-out user should land on the login page instead of seeing the content.

import { Navigate, useLocation, useNavigate, Routes, Route } from 'react-router-dom';

function RequireAuth({ user, children }) {
  const location = useLocation();
  if (!user) {
    return <Navigate to="/login" replace state={{ from: location }} />;
  }
  return children;
}

function LoginPage({ onLogin }) {
  const navigate = useNavigate();
  const location = useLocation();
  const goBackTo = location.state?.from?.pathname || '/dashboard';

  async function handleSubmit(event) {
    event.preventDefault();
    await onLogin(new FormData(event.currentTarget));
    navigate(goBackTo, { replace: true });
  }

  return <form onSubmit={handleSubmit}>{/* fields */}</form>;
}

<Routes>
  <Route path="/old-offers" element={<Navigate to="/offers" replace />} />
  <Route path="/dashboard" element={
    <RequireAuth user={user}><Dashboard /></RequireAuth>
  } />
</Routes>

Redirecting from code

useNavigate() returns a function. Call it with a path to move there, for example after saving a form or finishing a checkout. You can pass a number instead of a path: navigate(-1) goes back one entry in the history, just like the browser's back button.

Both tools accept a state option for passing data that should not appear in the URL. In the example, the protected route remembers where the user was heading, and the login page sends them back there afterwards.

Push or replace

By default, navigation pushes a new entry onto the browser history. With replace, the current entry is swapped out instead. Use replace for redirects the user should not return to. After login, for instance, pressing Back should not show the login form again, and a redirect from an old URL should not trap the user in a loop where Back immediately forwards them again.

If your app uses React Router's data routers with loaders and actions, there is a third option: return redirect('/login') from a loader or action. The redirect then happens before the component renders at all, which avoids briefly showing protected content.

Calling navigate at the wrong time

Calling navigate() directly in a component's body, outside an effect or handler, triggers a warning, because it changes the route while React is still rendering. If the redirect depends on rendering conditions, return <Navigate /> instead. If it must follow some asynchronous work, call it in the event handler or effect after that work finishes.

Another frequent issue is a redirect loop, where the login page redirects logged-in users to the dashboard while the dashboard redirects back because the user data has not loaded yet. Show a loading state while authentication status is unknown, and only redirect once you know the answer.

Takeaways

  • Render <Navigate> when the redirect depends on what would be shown.
  • Call navigate() from handlers or effects after an action completes.
  • Add replace for login and moved-page redirects.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course