Programmatic Navigation and Redirects
0 660
🚀 What Is Programmatic Navigation?
In React applications, programmatic navigation lets you navigate between pages using logic in your code — rather than just clicking links. This is useful for use cases like form submissions, login redirects, conditional routing, or logout flows. ðŸ§ðŸ“¦ React Router’s useNavigate Hook
React Router v6+ introduces theuseNavigate hook, replacing the older useHistory from v5. It gives you full control over routing in JavaScript.
import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
const goToDashboard = () => {
navigate('/dashboard');
};
return <button onClick={goToDashboard}>Go to Dashboard</button>;
}
🔠Navigating After Events
Programmatic navigation is commonly used after:- ✅ Form submissions
- ✅ Successful login/signup
- ✅ Completing a checkout
function handleSubmit(e) {
e.preventDefault();
// validate or send data
navigate('/success');
}
📥 Passing Data While Navigating
You can pass data usingstate:
navigate('/thank-you', { state: { userName: 'Aditya' } });
And retrieve it using the useLocation hook:
import { useLocation } from 'react-router-dom';
function ThankYouPage() {
const location = useLocation();
const { userName } = location.state || {};
return <h2>Thanks, {userName}!</h2>;
}
🔙 Navigating Backward or Forward
You can simulate browser history actions:
navigate(-1); // Go back
navigate(1); // Go forward
â›” Redirecting Unauthorized Users
To redirect users conditionally (e.g., if not logged in), just use:
if (!isLoggedIn) {
navigate('/login');
}
You can also use the <Navigate /> component for static redirects:
import { Navigate } from 'react-router-dom';
function PrivateRoute({ isAuth, children }) {
return isAuth ? children : <Navigate to="/login" replace />;
}
🧠Redirect on Mount
Use auseEffect for automatic redirection when a component mounts:
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
function RedirectPage() {
const navigate = useNavigate();
useEffect(() => {
navigate('/home');
}, []);
return null;
}
🧠Replace vs Push Navigation
By default,navigate() pushes to browser history. You can also replace the current entry:
navigate('/login', { replace: true }); // Won't keep previous page in history
This is useful for login redirects, so users can't press "Back" and go to the protected page again. ðŸ”
📋 Summary
- ✅ Use
useNavigate()for full control over navigation - ✅ Trigger redirects after events like login or submission
- ✅ Pass and receive data via
state - ✅ Replace history for secure redirects
- ✅ Use
<Navigate />for static route guarding
🚀 Final Thoughts
Programmatic navigation is a core part of building dynamic React applications. WithuseNavigate and <Navigate />, you can control user flow, enforce security, and build seamless UX transitions — all in just a few lines of code. 🔄⚛ï¸If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:




Comments
Waiting for your comments