Explain Codes LogoExplain Codes Logo

React-router go back a page how do you configure history?

javascript
react-router
history-api
navigation-patterns
Nikita BarsukovbyNikita Barsukov·Jan 27, 2025
TLDR

useHistory, a hook provided by React Router, can be used to navigate back through history.goBack().

import { useHistory } from 'react-router-dom'; function GoBackButton() { const history = useHistory(); return <button onClick={() => history.goBack()}>Go Back</button>; }

Press the Go Back button and voila! You're on the previous page.

Transition to useHistory in newer version

The more recent versions of React Router, especially v6, useNavigate replaces useHistory.

import { useNavigate } from 'react-router-dom'; function GoBackButton() { const navigate = useNavigate(); return <button onClick={() => navigate(-1)}>Go Back</button>; }

In single-page apps, calling navigate(-1) would mimic history.goBack(). Time travel made easy, isn't it? 😂

No hooks allowed in a class component party? Not to worry. The withRouter high-order component presents the history object:

import React from 'react'; import { withRouter } from 'react-router-dom'; class GoBackButton extends React.Component { render() { const { history } = this.props; return <button onClick={() => history.goBack()}>Go Back</button>; } } export default withRouter(GoBackButton);

Like a backstage pass at a concert, withRouter gives you access to all the good stuff.

Taking care of direct route access

In scenarios where users land directly on a page (say, via a bookmark or external link), a Go Back action could literally take them back to where they came from (yes, even to that e-commerce site where they last checked out dog food). Remember to have a fallback plan:

// If history can go back, awesome. If not, we fall back to the default path. function safeGoBack(defaultPath) { if (history.length > 1) { history.goBack(); } else { history.push(defaultPath); } }

Checking history state

Always be sure that the history state is in check. Especially when dealing with iframe scenarios, where browser history might be either isolated or non-existent.

Ensuring compatibility with React Suspense

Planning an upgrade to React Suspense or Concurrent mode? Ensure your history interactions are cool with the asynchronous workings of these more advanced features. Most of this tops talking about navigation actions as side effects.

Boasting ES6 and default exports

Show off your ES6 syntax skills for cleaner and more readable code. And keep the default exports in mind when you can.

export default function GoBackButton() { /* ... */ }

Making UX a bliss with Button History Navigation

A back button with clear history navigation is a major UX win. It's like breadcrumbs for the user, but digital and definitely not edible.

  • Button Highlight: Enemies spotted with onMouseOver.
  • Tooltip Info: PS5 restock not guaranteed: title="Go back to the previous page".
  • Button Unavailable: No breadcrumbs (history) left: disabled={!history.length}.

Advance Moves with React Router Patterns

Make use of advanced patterns for more granular control over back navigation:

  • Nested Routes: For those inception moments, nested routes provide relative navigation.
  • Auth Guards: Stop users from going back to protected pages, even after logout. "Access Denied!"
  • Custom Hooks: Can't get enough of hooks? Create a useBackNavigation hook for reuse and cleaner components.

The Dirty Details (or Edge Cases)

  • Detecting the end: Use history.length to decide to show the back button. Like a spoiler alert but for transitions.
  • Stay Put: Avoid accidental detours with event.preventDefault().
  • 404 handling: Ensure users can always turn back if they reach the dreaded 404 page.