React Navigation: useNavigate vs Navigate

🚀 Programmatic Navigation in React Router: useNavigate vs Navigate When building modern React apps, navigation isn’t always triggered by clicking a <Link />. Sometimes, you need to redirect users based on logic — after a form submission, authentication, or a condition. That’s where programmatic navigation comes in 👇 🔹 1. useNavigate (Imperative Navigation) Use this hook when you want to navigate after an action or event (e.g., button click, form submit). import { useNavigate } from "react-router-dom"; function Login() { const navigate = useNavigate(); function handleLogin() { // after successful login navigate("/dashboard"); } return <button onClick={handleLogin}>Login</button>; } 👉 Think of it as: "When this happens → go there." 🔹 2. <Navigate /> (Declarative Navigation) Use this when navigation depends on state or conditions during render. import { Navigate } from "react-router-dom"; function ProtectedRoute({ user }) { if (!user) return <Navigate to="/login" />; return <Dashboard />; } 👉 Think of it as: "If this is true → render a redirect." 💡 Key Difference useNavigate → triggered by events (imperative) <Navigate /> → triggered by state (declarative) 🔥 Pro Tip Use <Navigate /> for route protection and useNavigate for user-triggered flows like form submissions or button actions. Mastering both gives you full control over your app’s navigation flow — making your UI smarter and more dynamic 💪 #React #WebDevelopment #JavaScript #Frontend #ReactRouter #100DaysOfCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories