-1

i could not understand why handler in useEffect runs multiple times, i know that my useEffect runs for the first time but i didn't understand why handler in useEffect runs multiple times.

useEffect(() => {
    
    const keys = [];
    const handler = (e) => {
      
      keys.push(e.keyCode);

      const getItemsFiltered = keys
        .slice(0)
        .slice(Math.max(keys.length - 3, 0))
        .join("");

      if (getItemsFiltered == 1716113) {
        setShow(true);
      }
      console.log(getItemsFiltered);
      if (getItemsFiltered == 1716114) {
        document.getElementById("textField").focus();
      }
    };

    document.addEventListener("keydown", handler, false);
    return () => document.removeEventListener("keydown", handler, false);
  }, []);
saeid
  • 19
  • 3

1 Answers1

0

Your handler function reacts to every key press no matter where on the page you click! You can click in a section that's outside of your component, but your handler will still run because you attached your handler method as an event listener to the whole HTML page.

If you want to run the handler function only when you click on your component you can do the following:

document.getElementById("your-div-id").addEventListener("keydown", handler, false);

You can also use React's useRef hook to achieve the same effect.

Khairul
  • 79
  • 5
  • 1
    Querying the DOM is a React anti-pattern. I'd swap up your answer to only mention doing it as fallback if there are no other alternatives. Lead with using the React ref since it is the suggested method. – Drew Reese Jan 10 '23 at 10:25