Home » Solve – Export ‘useHistory’ was not found in react-router-dom

Solve – Export ‘useHistory’ was not found in react-router-dom

export usehistory was not found in react-router-dom

Today in this post, we are going to solve export ‘useHistory’ (imported as ‘useHistory’) was not found in ‘react-router-dom’ error in React JS.

Why export ‘useHistory’ was not found in react-router-dom Error Occur?

export usehistory was not found in react-router-dom error in React JS

We get this error because in react-router-dom v6 (version 6), the useHistory() hook is replaced by useNavigate() hook. We need to use useNavigate hook instead of useHistory hook.

The useNavigate() hook returns a function allowing us to navigate programmatically between pages.

How to solve export ‘useHistory’ was not found in react-router-dom error

import {useNavigate} from 'react-router-dom';
 
function Dashboard() {
  const navigate = useNavigate()

  const handleClick=()=>{
    //navigating to Home 
    navigate('/home')
  }

  return (
    <>
      <div>
        <button onClick={handleClick}>Go To Home</button>
      </div>
    </>
  );
}

export default Dashboard;

In the above code, we are using the “useNavigate()” hook to navigate from our Dashboard page to the home page. We are also replacing history.push with navigate function. The navigate function takes two parameters ‘to’ and ‘options’

If we want to replace the current entry in our history stack, we can pass options to our navigate function instead of using history.replace.

import {useNavigate} from 'react-router-dom';
 
function Dashboard() {
  const navigate = useNavigate()
 
  const handleClick=()=>{
    //navigating to Home
    navigate('/home', {replace: true})
  }
 
  return (
    <>
      <div>
        <button onClick={handleClick}>Go To Home</button>
      </div>
    </>
  );
}
 
export default Dashboard;

Here in the above code we are setting the ‘replace’ property to true on the options object. This will replace the current page in our history stack with the new page.

We can also pass additional data while redirecting to a new page. To send data we set our data to the ‘state’ property on the options object.

navigate('/home, { state: { userCount: '123' }})

Also check out:

Leave a Reply

Your email address will not be published.