javascriptreactjsreact-hookshistory.js

React JS history.listen not firing after page reload


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?


Solution

  • 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]);