How to use the useNavigate hook in React Router for programmatic navigation



Image not found!!

useNavigate is a hook provided by React Router for programmatic navigation. It allows you to navigate between different routes in your React application without needing to use the traditional history object. Here's how you can use useNavigate in your React application:

  1. Install React Router: If you haven't already, install React Router in your project:
bash
npm install react-router-dom
  1. Import useNavigate hook: Import useNavigate hook from react-router-dom in your component file where you want to use it.
javascript
import { useNavigate } from 'react-router-dom';
  1. Use useNavigate to navigate: Inside your component function, call useNavigate to get the navigate function, which you can use to navigate to different routes.
javascript
const MyComponent = () => { const navigate = useNavigate(); const handleClick = () => { navigate('/some-route'); // Navigates to '/some-route' }; return ( <div> <button onClick={handleClick}>Navigate</button> </div> ); };
  1. Conditional navigation: You can also conditionally navigate based on certain conditions in your component.
javascript
const MyComponent = ({ isAuthenticated }) => { const navigate = useNavigate(); const handleClick = () => { if (isAuthenticated) { navigate('/dashboard'); } else { navigate('/login'); } }; return ( <div> <button onClick={handleClick}>Navigate</button> </div> ); };

In this example, if the user is authenticated, clicking the button will navigate to the /dashboard route; otherwise, it will navigate to the /login route.

  1. Using navigate with parameters: You can also pass parameters to the navigate function to navigate to dynamic routes.
javascript
const MyComponent = () => { const navigate = useNavigate(); const handleDynamicClick = (id) => { navigate(`/items/${id}`); }; return ( <div> <button onClick={() => handleDynamicClick(123)}>Navigate to Item 123</button> </div> ); };

In this example, clicking the button will navigate to the /items/123 route.

With useNavigate, you can easily handle programmatic navigation in your React application without needing to rely on props drilling or context to access the history object.