Q:

How to access stateless component state inside window event listener?

I have a stateless component which needs to listen on keyboard event. It adds keydown listener when the component is mounted and remove it when the component is unmounted. There is a state test is boolean value. It is set to true when the component is mounted. But in the keydown event listener, its value always false. It looks like the listener doesn't take the state reference. What's wrong with my code?
const { useEffect, useState } = React;

const Comp = () => {
  const [test, setTest] = useState(false);
  const keyPressHandler = (e) => {
    setTest(!test);
    console.log(test);
  }
  useEffect(() => {
    setTest(true);
    window.addEventListener('keydown', keyPressHandler);
    return () => {
      window.removeEventListener('keydown', keyPressHandler);
    };
  }, []);

  return (
    <div className="test">
      hello {test + ""}
    </div>
  );
};

A:

You can re-run useEffect when test change which will make the listener always have the current value.
  useEffect(() => {
    setTest(true);
    window.addEventListener('keydown', keyPressHandler);
    return () => {
      window.removeEventListener('keydown', keyPressHandler);
    };
  }, [test]);

and you should remove the setTest from the useEffect since it will keep changing test to true whenever you use setTest().

