Home » React » 'useHistory' was not found in react-router-dom

'useHistory' was not found in react-router-dom

In version 6 of the react-router-dom library, the useHistory hook was replaced with the useNavigate hook. If you are using version 6 or higher and you are getting the error "export 'useHistory' was not found in 'react-router-dom'", you can use the useNavigate hook instead.

Resolve: 'useHistory' was not found in react-router-dom Error

The useNavigate hook returns a function that allows you to navigate to a different route programmatically. For example, you can use it to navigate to a new route after a form is submitted or when a button is clicked. To use the useNavigate hook, you can import it from react-router-dom and assign it to a variable, like this:

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

function MyComponent() {
  const navigate = useNavigate();
  // use navigate here
}

To navigate to a new route, you can call the navigate function and pass it the path of the route you want to navigate to. For example:

const handleClick = () => {
  navigate('/about');
};

return (
  <div>
    <button onClick={handleClick}>Navigate to About</button>
  </div>
);

The navigate function accepts an optional second argument, which is an options object that allows you to customize the behavior of the navigation. For example, you can use the replace property to replace the current entry in the history stack with the new one, like this:

const handleClick = () => {
  navigate('/about', { replace: true });
};

return (
  <div>
    <button onClick={handleClick}>Navigate to About</button>
  </div>
);

When the replace property is set to true, the current entry in the history stack is replaced with the new one, so if the user clicks the back button, they won't be able to navigate to the previous page. This can be useful, for example, when a user logs in or when you have a route that redirects users to a different page.

You can also call the navigate function with a delta to go back in the history stack. For example, navigate(-1) is equivalent to hitting the back button.

In conclusion, to solve the "export 'useHistory' (imported as 'useHistory') was not found in 'react-router-dom'" error, you can use the useNavigate hook instead. The useNavigate hook returns a function that allows you to navigate to a different route programmatically, and it also accepts an options object that allows you to customize the behavior of the navigation.

Related: