Home > Enterprise >  removeEventListener callback not being called for event (beforeunload)
removeEventListener callback not being called for event (beforeunload)

Time:09-07

Event listener beforeunload in not removing in useEffect, why it can happens?

import React, { useState, useEffect, FC } from 'react';

const beforeUnloadListener = (event: any) => {
  event.preventDefault();
  return (event.returnValue = 'Are you sure you want to exit?');
};

const OnClosePageDetector: FC = () => {
  useEffect(() => {
    window.addEventListener('beforeunload', beforeUnloadListener, { capture: true });
    return (): void => {
      window.removeEventListener('beforeunload', beforeUnloadListener);
    };
  }, []);

  return <div></div>;
};

export default OnClosePageDetector;

CodePudding user response:

Either remove capture: true from add event listener or add the same in remove event listener.

Also, In memory, it is possible that both add and remove are pointing to different locations due to different options provided.

The add event listener and remove event listener take the same param to work on a particular event. As we are registering the event listener- with the capture flag and removing without the flag, the side effects occur.

Reference

CodePudding user response:

solved, by removing param

{ capture: true }

CodePudding user response:

You can put the beforeUnloadListener function inside of the function given to useEffect (which is the recommended way of doing it according to the official documentation)

import React, { useState, useEffect, FC } from 'react';


const OnClosePageDetector: FC = () => {
    
  useEffect(() => {

    const beforeUnloadListener = (event: any) => {
        event.preventDefault();
        return (event.returnValue = 'Are you sure you want to exit?');
    };

    window.addEventListener('beforeunload', beforeUnloadListener, { capture: true });

    return (): void => window.removeEventListener('beforeunload', beforeUnloadListener);
    

  }, []);

  return <div></div>;
};

export default OnClosePageDetector;
  • Related