Going to the previous page is essential part of browsing experience.

In this article, we will explore how to implement a ‘go back’ feature in React.

How ‘go back’ feature works

Browsers keep track all URLs you visit when browsing a website. This information is stored in the history object, which can be accessed on the global window interface.

We’ll need to work with history object to implement ‘go back’ feature in React.

Go back in react-router v6

The newest (6th) version of react-router introduced the useNavigate() hook, and recommends using this hook to go back in React.

useNavigate() returns a function. To go back in react-router v6, simply call this function with one argument -1.

Let’s take a look at an example:

export default function App() {
  const navigate = useNavigate();
  return (
    <div>
      <Link to="/1">Go to page 1</Link>
      <Link to="/2">Go to page 2</Link>
      <Link to="/3">Go to page 3</Link>

      <button onClick={() => navigate(-1)}>Go back</button>
    </div>
  );
}

1. We create a variable to store function returned by useNavigate() hook

2. Call that function

3. To go back one step, pass it an argument of -1. If you want to go back two steps, pass it -2.

You can only use the useNavigate() hook if the component is a descendant of <Router> (for web applications, <BrowserRouter> ) component.

Go back in react-router v4 and v5

In react-router versions 4 and 5, we have the useHistory() hook, which returns reference to the history object.

Calling the goBack() method on history takes users to the previous URL.

Let’s take a look at an example:

export default function App() {
  const history = useHistory();
  return (
    <div>
      <Link to="/1">Go to page 1</Link>
      <Link to="/2">Go to page 2</Link>
      <Link to="/3">Go to page 3</Link>

      <button onClick={() => history.goBack()}>Go back</button>
    </div>
  );
}

In this example, clicking the button makes users go back to previous page.

To implement go back in react-router versions 4 and 5, you need to:

  1. Create a variable (in this example, named history)  to store the result of useHistory() hook.
  2. In the event handler, call the goBack() method on history variable.

You don’t need to pass any arguments to the goBack() method.

It is not a requirement to use <button> element. You can also use <span>, <p> <div> or other elements. You can even call history.goBack() in the useEffect() function.