useHistory Hooks

The useHistory hook is provided by the React Router library, specifically react-router-dom, to access and manipulate the browser history. It allows you to programmatically navigate, push, replace, or go back and forth in the history stack of the application.

Here's an example of how to use the useHistory hook:

In this example, the useHistory hook from react-router-dom is used to access the history object. The history object allows you to perform various navigation actions.

The history.push ('/new-route') function call navigates to the specified route, in this case, /new-route. It updates the URL and adds a new entry to the history stack, allowing the user to navigate back to the previous route using the browser's back button.

Other functions provided by the history object include:

1. history.replace('/new-route')

Replaces the current route with the specified route in the history stack, without adding a new entry. This can be useful for scenarios like form submissions, where you don't want the user to navigate back to the previous route.

2. history.goBack()

Navigates back to the previous route in the history stack, equivalent to clicking the browser's back button.

3. history.go(n)

Navigates to a specific position in the history stack, where n can be a positive or negative integer representing the number of steps to go forward or backward.

Make sure you have set up your routing configuration correctly using a library like React Router or reach-router. Also, ensure that your component is rendered within a <Router> component to access the history object.

Remember to import the useHistory hook from the react-router-dom module.


To navigate to a different route, you can use the push method of the history object. For example, to navigate to the '/dashboard' route, you can use history.push('/dashboard');.

To go back to the previous page, you can use the goBack method of the history object, like this: history.goBack();.

No, the useHistory Hook can only be used within components that are part of the React Router's component tree. It relies on React Router's context to provide access to the history object.