DEV Community

builtbyjosh
builtbyjosh

Posted on

What is useHistory()?

Another great hook that is available to React is the useHistory() hook. This hook gives you access to the history object from react-router-dom, which you can use to navigate. The useHistory hook then allow you to set navigate programmatically to other routes in your application by using push and replace methods.

To use this hook, you will first need to install react-router-dom.

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

Once installed, you will need to import useHistory into your app and create a history variable.

Import { useHistory } from ‘react-router-dom

const history = useHistory()
Enter fullscreen mode Exit fullscreen mode

With the history variable created, you can now “push” routes to the history object. This will cause your application to navigate to that pushed location. This is usually handled with a function that can attached to the onClick event on a button or link

const goHome = () => {
    history.push(“/”)
}

<button onClick={goHome}>Home</button>
Enter fullscreen mode Exit fullscreen mode

Now, when the home button is clicked, your app will redirect to the component that is set to the “/” route. Besides the import call, all of this will need to be created inside of the functional component. And as a whole, it may look something like this:

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

const App = () => {
    const history = useHistory();

    const goHome = () => {
        history.push("/");
    }

    return (
        <div>
          <h1>Hi there!</h1>
          <button onClick={goHome}>Home</button>
        </div>
    );
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)