useHistory hook needs no introduction. It’s one of the most useful hooks for navigation in React.

So let’s see how to (and if we can) use it in React Router 6.

useHistory in React Router v6

React developers used useHistory to programmatically navigate from one page to another.

The newest react router 6 handles navigation a little differently.

Instead of useHistory, developers introduced useNavigate() that provides much simpler syntax for navigation between pages in React.

Let’s look at an example:

function App() {
  const navigate = useNavigate();
  return (
    <div className="App">
      <button onClick={() => navigate("/another-page")}>
        Go to another page

As you can see, the useNavigate() hook returns a function that allows you to navigate from one page to another. We store this function in navigate variable.

At this point, you can call navigate() function anywhere in your code. Even inside JSX. Its argument needs to be the relative path to which you want to navigate.

In this case, we use navigate() function in an event handler for click events. Whenever users click the button, react router will redirect them to specified path.

In my opinion, useNavigate() is more readable and straightforward than using history object to programmatically change the URL.