DEV Community


Posted on

useHistory - REACT ROUTER

React rendering lifecycle:

  1. The Redirect component must be returned
  2. The Redirect is then rendered
  3. The URL is then updated
  4. And finally the appropriate route is rendered.

React Router also provides a mechanism for updating the browser’s location imperatively: the Router‘s history object which is accessible via the useHistory() hook.

import { useHistory } from 'react-router-dom';
Enter fullscreen mode Exit fullscreen mode

The history object that useHistory() returns has a number of methods for imperatively redirecting users. The first and most straightforward is history.push(location) which redirects the user to the provided location.

Consider this example which immediately triggers a redirect back to the / page after a user successfully submits a

import { useHistory } from `react-router-dom`

export const ExampleForm = () => {

  const history = useHistory()

  const handleSubmit = e => {

  return (
    <form onSubmit={handleSubmit}>
      {/* form elements */ }

By enabling imperative updates to the browser location, the history object allows you to respond immediately to user input without having to wait.

You might be wondering how the history object works. Internally, the BrowserRouter‘s history object uses the html5 history API.

In brief, browser history is a stack that stores the URLs visited by the user and maintains a pointer to the user’s current location. This history API allows you to navigate through a user’s session history and alter the history stack if necessary.

In addition to history.push(), the history object has a few more useful methods for navigating through the browser’s history:

history.goBack() which navigates to the previous URL in the history stack
history.goForward() which navigates to the next URL in the history stack
history.go(n) which navigates n entries (where positive n values are forward and negative n values are backward) through the history stack
Below, we can see how the .goBack() method is used to create a “Go Back” button:

import { useHistory } from `react-router-dom`

export const BackButton = () => {
  const history = useHistory()

  return (
    <button onClick={() => history.goBack()}>
      Go Back

Top comments (0)