Home > Net >  event listener not removing in UseEffect (removeEventListener)
event listener not removing in UseEffect (removeEventListener)

Time:09-06

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:

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