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:
bashnpm install react-router-dom
useNavigate
hook: Import useNavigate
hook from react-router-dom
in your component file where you want to use it.javascriptimport { useNavigate } from 'react-router-dom';
useNavigate
to navigate: Inside your component function, call useNavigate
to get the navigate
function, which you can use to navigate to different routes.javascriptconst MyComponent = () => {
const navigate = useNavigate();
const handleClick = () => {
navigate('/some-route'); // Navigates to '/some-route'
};
return (
<div>
<button onClick={handleClick}>Navigate</button>
</div>
);
};
javascriptconst 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.
javascriptconst 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.