How to use React's useHistory() hook

The useHistory hook allows us to access React Router's history object.

Through the history object, we can access and manipulate the current state of the browser history.

All we need to do is to call the useHistory hook inside a functional component:

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

const App = () => {
  const history = useHistory();

  const redirect = () => {
    history.push('/login');
  }

  return (
    <div>
      <h1>Hi there!</h1>
      <button onClick={redirect}>Log in</button>
    </div>
  );
};

We can use this object to redirect the user to another page by calling history.push('/example-route').

The default history prop

If a component doesn't accept any props, React Router will add the history prop by default.

So in our App component from above, we could do the following:

const App = ({ history }) => {
  const redirect = () => {
    history.push('/login');
  }

  return (
    <div>
      <h1>Hi there!</h1>
      <button onClick={redirect}>Log in</button>
    </div>
  );
};

As soon as we add another property, however, the history prop will be undefined. In this case, we'd need to use the useHistory hook again.

This approach seems inconvenient to me, as you will often add props to a component later on. That's why I recommend you use the useHistory hook in any case.

Conclusion

This hook makes using React Router together with functional components effortless.

If you have any open questions or feedback, please leave a comment below, so I know how I can improve this article.

If you liked this article, you might also want to check out my other articles about React:

Support

PatreonKoFi