TypeOfNaN

Programmatically Navigate Using React Router and Hooks

Nick Scialli
May 23, 2020

New — Check out my free newsletter on how the web works!

react router logo

If you’re using React Router 5.1.0 or later and React 16.8.0 or later, you can now programmatically navigate with ease using the useHistory hook!

Let’s look at a quick example. Say you want to navigate somewhere on a button click. Previously, you might have had to pass the history object down your React component tree. With the new useHistory hook, you no longer need to do that!

import { useHistory } from 'react-router-dom';

function MyComponent() {
  const history = useHistory();

  function goToLogin() {
    history.push('/login');
  }

  return (
    <button type="button" onClick={goToLogin}>
      Login
    </button>
  );
}

And there you have it! We’ve retrieved our history object using a hook inside our function component. We can now use the push method on history to navigate the user somewhere!

🎓 Learn how the web works

One of the best ways to level up your tech career is to have a great foundational understanding of how the web works. In my free newsletter, How the Web Works, I provide simple, bite-sized explanations for various web topics that can help you boost your knowledge. Join 2,500+ other learners on the newsletter today!

Signing up is free, I never spam, and you can unsubscribe any time. You won't regret it!

Sign up for the newsletter »
Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli