useNavigate()
useNavigate() is a hook provided by React Router.
It allows us to navigate from one route to another using JavaScript.
For example, imagine we have:
/home
/about
/contact
If I want to move to /about when a button is clicked, I can use useNavigate().
import { useNavigate } from "react-router-dom";
function Home() {
const navigate = useNavigate();
return (
<button onClick={() => navigate("/about")}>
Go to About
</button>
);
}
export default Home;
Why do we need useNavigate()?
This was the part that helped me understand it better.Sometimes navigation should happen after some action.
For example:
After login → go to Dashboard
After form submission → go to Success page
After logout → go to Login page
After completing a quiz → go to Result page
In these situations, we don't just want a normal link.We want navigation to happen based on some logic.
That's where useNavigate() becomes useful.
Here,
const navigate = useNavigate();gives us a navigate function.
Then navigate("/about");means “Go to the /about route.”
Top comments (0)