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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

Fix - 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> ); }

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> ); }

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 uses to a different page - 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.

Use the search field on my Home Page to filter through my more than 3,000 articles.