React JS history.listen not firing after page reload

249 views Asked by At

I am listening to React history changes in my component like this:

const history = useHistory();
useEffect(() => {
  history.listen(() => { // do something here});
}, [history]);

It works as long as page is not reloaded. When i reload the page history.listen callback does not fire. Can anyone point out how can i fix this?

2

There are 2 answers

5
Ori Drori On BEST ANSWER

From the history point of view no action was fired after refresh. If you want to call the listener on mount, just call it directly in the useEffect:

const history = useHistory();

useEffect(() => {
  const listener = () => { // do something here};
  history.listen(listener);
  listener();
}, [history]);
0
Fotios Tsakiris On

Use the window.addEventListener method to listen to the popstate event.


const handleHistoryChange = () => {
  // do something here
}

useEffect(() => {
  window.addEventListener('popstate', handleHistoryChange);

  return () => {
    window.removeEventListener('popstate', handleHistoryChange);
  };
}, []);