DEV Community

Rahil Vahora
Rahil Vahora

Posted on

How to Redirect Users Dynamically and Pass State Like a Pro

Mastering React Router: useNavigate & useLocation for Seamless Navigation


πŸ”Ή Introduction

In modern React applications, handling dynamic navigation and redirections is a must. Imagine this scenario:

πŸ”Ή A user tries to apply on the job link without logging in.

πŸ”Ή They are redirected to the login page.

πŸ”Ή After login, they should return to their job application page but guess what they land on the home page.

To achieve this, React Router provides two powerful hooks:

βœ… useNavigate - For programmatic navigation.

βœ… useLocation - To access the current route and retrieve stored state.

In this article, we’ll explore why useNavigate and useLocation are essential, how they work, and how to use them to store and retrieve state during redirections.


πŸš€ What is useNavigate?

useNavigate is a React Router hook that allows you to programmatically navigate between pages.

πŸ“Œ Basic Usage

import { useNavigate } from "react-router-dom";

const Home = () => {
    const navigate = useNavigate();

    return (
        <div>
            <h1>Home Page</h1>
            <button onClick={() => navigate("/dashboard")}>Go to Dashboard</button>
        </div>
    );
};
Enter fullscreen mode Exit fullscreen mode

βœ… Clicking the button redirects the user to /dashboard.

πŸ“Œ Navigating with State

Sometimes, we want to pass additional data when navigating.

navigate("/dashboard", { state: { userId: 123, role: "admin" } });
Enter fullscreen mode Exit fullscreen mode

πŸš€ What is useLocation?

useLocation lets us access the current route details, including:

  • pathname – The current page URL.
  • state – Data stored when navigating.

πŸ“Œ Basic Usage

import { useLocation } from "react-router-dom";

const Dashboard = () => {
    const location = useLocation();

    return (
        <div>
            <h1>Dashboard</h1>
            <p>Current URL: {location.pathname}</p>
            <p>Data from Previous Page: {JSON.stringify(location.state)}</p>
        </div>
    );
};
Enter fullscreen mode Exit fullscreen mode

βœ… If navigated using:

navigate("/dashboard", { state: { userId: 123, role: "admin" } });
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ The dashboard retrieves the user data from location.state.


πŸš€ Real-World Example: Redirecting Users After Login

Let's say a job portal allows users to apply for jobs, but they must log in first.

πŸ›  Scenario

1️⃣ A user clicks "Apply for Job" but is not logged in.

2️⃣ They are redirected to the login page.

3️⃣ After login, they should return to the job application page.


πŸ”Ή Step 1: Store Intended Route Before Redirecting (JobDetails.js)

import { useNavigate } from "react-router-dom";

const JobDetails = () => {
    const navigate = useNavigate();

    const handleApply = () => {
        navigate("/login", { state: { redirectTo: "/job-details/123" } });
    };

    return (
        <div>
            <h1>Software Engineer Job</h1>
            <button onClick={handleApply}>Apply Now</button>
        </div>
    );
};

export default JobDetails;
Enter fullscreen mode Exit fullscreen mode

βœ… What Happens?

  • The user is redirected to /login.
  • The intended route (/job-details/123) is stored in location.state.

πŸ”Ή Step 2: Retrieve Stored Route After Login (Login.js)

import { useNavigate, useLocation } from "react-router-dom";
import { useContext } from "react";
import { authContext } from "../context/AuthContext";

const Login = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const { login } = useContext(authContext);

    const redirectTo = location.state?.redirectTo || "/";

    const handleLogin = () => {
        login("mockAccessToken"); // Simulating login
        alert("Login successful!");

        navigate(redirectTo, { replace: true });
    };

    return (
        <div>
            <h1>Login Page</h1>
            <button onClick={handleLogin}>Login</button>
        </div>
    );
};

export default Login;
Enter fullscreen mode Exit fullscreen mode

βœ… What Happens?

  • location.state?.redirectTo retrieves the intended page.
  • If it exists, the user is redirected back to /job-details/123.
  • If no stored state, the user goes to the homepage (/).

πŸ”₯ Summary: How useNavigate and useLocation Work Together

Step Action Stored Data Accessed Via
1️⃣ User clicks "Apply Now" { redirectTo: "/job-details/123" } useNavigate("/login", { state: { redirectTo: "/job-details/123" } })
2️⃣ User is redirected to /login { redirectTo: "/job-details/123" } is stored Available in useLocation().state
3️⃣ After login, user is redirected back `location.state?.redirectTo

πŸ”₯ Example: Passing Product Data Instead of Redirects

Instead of passing redirection paths, we can pass other state values.

πŸ“Œ Step 1: Send Product Data ({% raw %}Product.js)

navigate("/checkout", { state: { productId: "123", price: 299 } });
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Step 2: Retrieve Data (Checkout.js)

const location = useLocation();
console.log(location.state?.productId, location.state?.price);
Enter fullscreen mode Exit fullscreen mode

βœ… No global state or URL parameters needed!


🎯 Final Thoughts

React Router’s useNavigate and useLocation are essential for:

βœ… Redirecting users dynamically (e.g., after login).

βœ… Storing & retrieving state without global state management.

βœ… Passing data between components easily.

πŸ’‘ Now that you understand these hooks, how will you use them in your next React project?

πŸ”₯ Drop a comment below if you have any questions! πŸš€

Top comments (0)