Skip to main content

navigate in react router dom

React Router DOM provides two primary mechanisms for programmatic navigation: the useNavigate hook and the Navigate component.
1. useNavigate Hook:
The useNavigate hook is used within functional components to obtain a navigate function, which can then be called to programmatically change the route. This is ideal for navigation triggered by events like button clicks, form submissions, or other interactive user actions.
Code

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

function MyComponent() {
  const navigate = useNavigate();

  const handleClick = () => {
    navigate('/dashboard'); // Navigates to the /dashboard path
  };

  const handleLoginSuccess = () => {
    navigate('/home', { replace: true }); // Navigates to /home and replaces the current history entry
  };

  const goBack = () => {
    navigate(-1); // Navigates back one step in browser history
  };

  return (
    <button onClick={handleClick}>Go to Dashboard</button>
  );
}
2. Navigate Component:
The Navigate component is used for declarative navigation, typically for redirects based on certain conditions during the render process. It automatically navigates the user when rendered.
Code

import { Navigate } from 'react-router-dom';

function ProtectedRoute({ isAuthenticated }) {
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />; // Redirects to /login if not authenticated
  }
  return <div>Protected content</div>;
}
Key Differences: 
useNavigate (Imperative): Used for navigation triggered by events or logic within a function.
Navigate (Declarative): Used for conditional or automatic navigation during the rendering of a component.