Julia M
Julia M

Reputation: 51

How to remove event listener manually in React

I'm using react hooks and I want to conditionally add and remove listener (not only in case my component unmounts). My component adds the listener however never removes it. Why is it so?

useEffect(() => {
    if (isPlaying) {
      document.addEventListener('keydown', handleKeyPress);
    }

    if (!isPlaying) {
      document.removeEventListener('keydown', handleKeyPress);
    }

    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, []);

Upvotes: 2

Views: 2569

Answers (1)

Julia M
Julia M

Reputation: 51

The problem is that I forgot to resubscribe for isPlaying property. Without any argument, useEffect runs only once and then clears on destroy. In the code above, useEffect is called as it does in componentDidMount, and by chance, isPlaying property equals to true, so the eventListener is added. But when isPlaying becomes falsy, the useEffect is never called again and obviously, never removes the eventlistener. The fix is to pass isPlaying as a second argument to useEffect:

... return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, [isPlaying]);

Upvotes: 2

Related Questions