[Fixed] Attempted import error: ‘useHistory’ is not exported from ‘react-router-dom’

In this tutorial, you will learn to fix the error “Attempted import error: ‘useHistory’ is not exported from ‘react-router-dom'” that is usually observed in reactJS application.

The useHistory hook provides you with access to a history instance that you can use to navigate through the application. When you install React Router, you’ll find a few hooks that allow you to access the current state of the router and navigate through it from within your components.

Fix Attempted import error: ‘useHistory’ is not exported from ‘react-router-dom’ Error

Note that you will need to use the React version greater than 16.8 in order to properly integrate hooks in your react application.

Let us see an example useHistory usage in ReactJS inside your application.

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

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go Back To Home Page
    </button>
  );
}

Now to the problem you are facing and how to fix that. useHistory() has been replaced by useNavigate() in the react-router-dom v6. So you will need to use the below mentioned code.

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

function HomeButton() {
  const navigate = useNavigate();

  function handleClick() {
    navigate("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go Back To Home Page
    </button>
  );
}

Or simply upgrade your React version to 5.2.0 and it should work.

Wrap Up

I hope you were able to correct the above-mentioned error. Because useHistory is deprecated in the new version of the react version, I provided a proper solution of using useNavigate instead of useHistory.

If you know of a better method than the one discussed above, please let me know in the comments section and I will gladly add it here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. [Fixed] Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’

Leave a Comment