skip to Main Content

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

Answers


  1. 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]);
    
    Login or Signup to reply.
  2. 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);
      };
    }, []);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search