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>
);
};
β
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" } });
π 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>
);
};
β
If navigated using:
navigate("/dashboard", { state: { userId: 123, role: "admin" } });
π 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;
β What Happens?
- The user is redirected to
/login
. - The intended route (
/job-details/123
) is stored inlocation.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;
β 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 } });
π Step 2: Retrieve Data (Checkout.js
)
const location = useLocation();
console.log(location.state?.productId, location.state?.price);
β 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)