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

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

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

To solve the error "export 'useHistory' (imported as 'useHistory') was not found in 'react-router-dom'", use the useNavigate hook instead, e.g. const navigate = useNavigate().

The hook returns a function that lets you navigate programmatically.

export usehistory was not found in react router-dom

App.js
// ๐Ÿ‘‡๏ธ import useNavigate import {useNavigate} from 'react-router-dom'; export default function App() { const navigate = useNavigate(); const handleClick = () => { // ๐Ÿ‘‡๏ธ Navigate programmatically navigate('/about'); }; return ( <div> <button onClick={handleClick}>Navigate to About</button> </div> ); }

import and use use navigate hook

The code for this article is available on GitHub

In version 6 of React Router, the useHistory() hook is replaced with useNavigate().

The useNavigate hook returns a function that lets us navigate programmatically, e.g. after a form is submitted.

The parameter we passed to the navigate function is the same as the to prop on a <Link to="/about"> component.

If you want to use the equivalent of the history.replace() method, pass an options parameter to the navigate function.

App.js
import {useNavigate} from 'react-router-dom'; export default function App() { const navigate = useNavigate(); const handleClick = () => { // ๐Ÿ‘‡๏ธ Replace set to true navigate('/about', {replace: true}); }; return ( <div> <button onClick={handleClick}>Navigate to About</button> </div> ); }

passing options object to navigate

The code for this article is available on GitHub

When the replace property is set to true on the options object, the current entry in the history stack gets replaced with the new one.

In other words, navigating to the new route won't push a new entry into the history stack, so if the user clicks the back button, they won't be able to navigate to the previous page.

This is useful, for example, when a user logs in - you don't want them to be able to click the back button and get back to the login page.

Or if you have a route that redirects to a different page. Then you don't want users to click the back button and get redirected again.

You can also call the navigate function with a delta to go back in the history stack, e.g. navigate(-1) is the same as hitting the back button.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev