Home > Software design >  why does my event run multiple times in useEffect?
why does my event run multiple times in useEffect?

Time:01-10

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);
  }, []);

CodePudding user response:

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.

  • Related