score:0

the best way to go about such scenarios is to see what you are doing in the event handler. if you are simply setting a state using the previous state, it's best to use the callback pattern and register the event listeners only on the initial mount. if you do not use the callback pattern (https://reactjs.org/docs/hooks-reference.html#usecallback) the listeners reference along with its lexical scope is being used by the event listener but a new function is created with updated closure on new render and hence in the handler you will not be able to the updated state

const [usertext, setusertext] = usestate('');

  const handleuserkeypress = usecallback(event => {
    const { key, keycode } = event;

    if (keycode === 32 || (keycode >= 65 && keycode <= 90)) {
      setusertext(prevusertext => `${prevusertext}${key}`);
    }
  }, []);

  useeffect(() => {
    window.addeventlistener('keydown', handleuserkeypress);

    return () => {
      window.removeeventlistener('keydown', handleuserkeypress);
    };
  }, [handleuserkeypress]);

  return (
    <div>
      <h1>feel free to type!</h1>
      <blockquote>{usertext}</blockquote>
    </div>
  );

according to this answer : https://stackoverflow.com/a/55566585/6845743

score:0

i think i figured out the issue, it was entirely my fault and the way i wrote my component.

minimal example https://codesandbox.io/s/strange-nobel-l6eqe?file=/src/app.js

it's a lot more obvious here, but essentially the component where the listener was created wasn't actually being unmounted, i was just unmounting its contents which obviously meant the listener wasn't getting removed.

solutions are:

  1. don't write your component like this
  2. move the listener inside a child component

score:0

keep the handler outside useeffect, that should work. we would just be attaching that function on mount and removing on unmount.


const component = () => {
 const handler = (e: keyboardevent) => {
      if (e.iscomposing || e.keycode === 27) {
        console.log('do something');
      }
    };

  useeffect(() => {
       window.addeventlistener('keydown', handler, false);
    return () => window.removeeventlistener('keydown', handler, false);
  }, []);

  return <div />;
};


Related Query

More Query from same tag