`window.removeEventListener('keydown')` doesn't work in react hooks function

Keywords: reactjs


I am using react hooks inside a stateless component. Below is the source code:

const MyComp = ({focused}) => {
const keyPressListener = (e: KeyboardEvent) => {
    console.log('key press:', e);

useEffect(() => {
    if (focused) {
      console.log('add event listener');
      window.addEventListener('keydown', keyPressListener);
    } else {
      console.log('remove event listener');
      window.removeEventListener('keydown', keyPressListener);
  }, [focused]);

It listens on the property focused. It adds keydown listener when it is true and remove it when it becomes false. I can see the console log about add/remove event listener but the keyPressListener function is still called after remove. I see many people have the same issue because they didn't bind the function. But I don't think it is needed for arrow function in this case.