React › Routing
How would you programmatically navigate a user to a different page after they complete an action, such as submitting a form?
IntermediateAnswer
React Router provides a useNavigate hook that gives you a function to change the current page directly from your code, instead of relying on the user clicking a link, which is useful right after a successful form submission or login.
import { useNavigate } from 'react-router-dom';
function LoginForm() {
const navigate = useNavigate();
function handleLogin() {
loginUser().then(() => navigate('/dashboard'));
}
return <button onClick={handleLogin}>Log In</button>;
}Real-world example A checkout page automatically redirects a customer to an order confirmation page the moment their payment is successfully processed, using useNavigate instead of requiring the customer to click a link themselves.