React router history push is ignored by browser back button

  history, javascript, reactjs, router

I use the BrowserRouter for a React app.
I import the history like this:

import { useHistory } from 'react-router-dom';

I then ‘get’ the history with a hook in my component, like this:

const history = useHistory();

In my component, I modify the url inside a useEffect() function like this:

const urlParams = new URLSearchParams();
urlParams.append('number', i);
history.push({ search: urlParams.toString() });

This works fine. After clicking a button in my component I can see the browser url changing, from myurl.com/?number=0 to myurl.com/?number=1

However, when clicking the browser’s back button, the browser url is updated (good), but the component isn’t re-rendered. In effect, nothing happens.

I would like for the back button to reload the component/page, i.e. navigating from myurl.com/?number=1 to myurl.com/?number=0 (for example).

What am I missing? I tried pushing not only search, but also pathname, but to no avail.

Source: Ask Javascript Questions

LEAVE A COMMENT