Home > OS >  React router - useHistory / useNavigate vs window.history.back()
React router - useHistory / useNavigate vs window.history.back()

Time:09-19

I have a navigate back button and while checking for returning back I found two ways:

  1. The native way:
window.history.back()

or

window.history.go(-1)
  1. The react router way:
export const BackButton: FC = () => {
  const navigate = useNavigate();

  return (
      <button
        onClick={() => navigate(-1)}>
          Back
      </button>
  );
}

or for v5

export const BackButton: FC = () => {
  const { goBack } = useHistory();

  return (
      <button
        onClick={goBack}>
          Back
      </button>
  );
}

So I am wondering what is the differences between these ways.

I am guessing (didn't check the source code) that under the hood react router use the native way and do a bit more things, and if I am using react router then I should use the react router way but I still would like to understand the differences.

Thanks!

CodePudding user response:

In react window.history.back() change the URL and load page while useNavigate or useHistory just re-render components that's why it is better to use it.

CodePudding user response:

They all map back to the window.history object. goBack also is implemented as go(-1). The main difference between using the window.history object and using the react-router history object (v5) or navigate function (v6) is that using window.history will effect navigation changes outside of React and react-router whereas using history or navigate will be correctly handled internally by react-router to update its internal routing context prior to effecting the change with the Browser.

Think of the window.history "way" as a sort of "global mutation" that React wouldn't be aware of or be able to handle well.

Using window.history will reload the page whereas using react-router will only update the URL in the address bar and render/rerender routes/etc internally within the app, i.e. there is no page reload and the app remains mounted and running the entire time.

  • Related