React router history push is ignored by browser back button

Viewed 799

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.

1 Answers

There is one thing to keep in mind here that you are not changing the base route instead just changing the query parameter. And as the component against that base url is already mounted it will not be re-rendered logically.

For cases like that, there can be couple of approaches.

  1. You can use useEffect(()=>{}, [number]), so anytime the search param changes, this hook will be called and you can do whatever you intend. Note:

number => just a variable containing the value for query parameter

Like this:

const urlParams = new URLSearchParams();

const number = urlParams.get('number');
Related