useNavigate: Programmatic Navigation in React
The `useNavigate` hook gives you a function to change routes from your component's logic, like after a form submission. Use it for event-driven navigation, such as sending a user to their dashboard after login.
WHY IT EXISTS React Router's <Link> component handles user-clicked navigation. But systems often need to navigate based on code logic, like redirecting after a successful API call. useNavigate provides this imperative API for client-side routing from within your components.
THE MENTAL MODEL Think of useNavigate as a remote control for the browser's address bar that you can use from your JavaScript code. While a <Link> is a visible button for the user, the navigate function is something you call yourself when a certain condition is met, like a form being successfully submitted.
HOW IT WORKS Call useNavigate() at the top level of your component to get a navigate function. You can call this function in a few ways. First, with a string path like navigate('/dashboard'). Second, with a number to move through the browser's session history, like navigate(-1) to go back. Third, with an options object to modify the navigation, such as navigate('/home', { replace: true }) to prevent the user from returning to the current page via the back button.
WHEN TO USE IT Use useNavigate for navigation triggered by component logic. Common cases include: redirecting a user after a successful form submission (e.g., login or signup), creating a "Go Back" button that calls navigate(-1), or programmatically advancing a user through a multi-step wizard.
WHEN NOT TO USE IT For standard navigation, always prefer the declarative <Link> component for accessibility. Inside modern React Router loader or action functions, it is better to return redirect('/path') than to use this hook. useNavigate is for client-side component logic, not data-layer redirects.
ONE CANONICAL EXAMPLE To redirect a user after a successful login and prevent them from going back to the login page, you would use the replace option. Inside your component: const navigate = useNavigate(); const handleLogin = async () => { const success = await api.login(credentials); if (success) { navigate('/dashboard', { replace: true }); } }; This replaces the login page in the history stack with the dashboard page.
Read the original → api.reactrouter.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.