0
  const [key, setKey] = useState<string | null>(null);

  const pointerLocation = useRef(0);

  useEffect(() => {
    console.count("key listener");
    const handleKeyDown = (e: KeyboardEvent) => {
      setKey(e.key);
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [key]);

  useEffect(() => {
    const letter = document.getElementsByClassName("letter");
    if (key) {
      if (letter[pointerLocation.current] && key.length === 1) {
        letter[pointerLocation.current].textContent = key;
        pointerLocation.current++;
      }
    }

    if (key === "Backspace") {
      if (letter[pointerLocation.current - 1]) {
        letter[pointerLocation.current - 1].textContent = "";
        pointerLocation.current--;
      }
    }
  }, [key, pointerLocation]);

The second useEffect hook only runs when the key state value changes, even if the new value is the same as the previous one. This means that if a user presses the same key twice, the second useEffect hook won't run again, and the text won't update as expected.

I tried to change the dependency array of the second useEffect hook to include the pointerLocation variable as well, hoping that the effect would be triggered whenever either key or pointerLocation changes. However, this did not work since the pointerLocation variable is not being updated anywhere in the component.

I also tried to add a random number to the key state variable whenever it is updated to the same value, hoping that it would trigger the effect. However, this caused unnecessary re-renders and was not an optimal solution.

Matt Yak
  • 35
  • 4
  • The reason why `pointerLocation` doesn't trigger the `useEffect`: https://stackoverflow.com/a/60476525/15291770 I'm interested as to why you're manually handling keyboard inputs, could you expand a little more on that? – Harrison Apr 13 '23 at 14:30
  • 2
    This feels like an XY problem. Why are you storing the key as a state? Shouldn’t you invoke the logic associated with key press directly inside the handlers themselves? The useEffect works as expected: pressing a key more than once will not trigger any change since the key is the same. – Terry Apr 13 '23 at 14:30
  • @Harrison I am manually handling keyboard inputs so that the user does not need to focus on an input box to send an input. Anywhere on the page that a key is pressed, the letters will update. – Matt Yak Apr 13 '23 at 14:39

0 Answers0