I have a navigate back button and while checking for returning back I found two ways:
- The native way:
window.history.back()
or
window.history.go(-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!
2
Answers
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.
They all map back to the
window.history
object.goBack
also is implemented asgo(-1)
. The main difference between using thewindow.history
object and using thereact-router
history
object (v5) ornavigate
function (v6) is that usingwindow.history
will effect navigation changes outside of React andreact-router
whereas usinghistory
ornavigate
will be correctly handled internally byreact-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 usingreact-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.