Home > database >  How could a function registered in an effect hook run though an empty array dependency is passed to
How could a function registered in an effect hook run though an empty array dependency is passed to

Time:12-01

I have a registered onmousemove event in useEffect as follows. But in order not to run the effect every time the component renders I pass it an empty array dependency. But still the function that handles the event is called. But the function is inside useEffect. How could this be possible?


import { useEffect, useState } from "react";

const UseEffect1 = () => {
  const [X, setX] = useState(0);
  const [Y, setY] = useState(0);

  const handleMouseMove = (e) => {
    setX(e.clientX);
    setY(e.clientY);
  };

  useEffect(() => {
    window.addEventListener("onmousemove", handleMouseMove);
  }, []);

  return (
    <div>
      <p>
        width {X} - height {Y}
      </p>
    </div>
  );
};

export default UseEffect1;

CodePudding user response:

The useEffect hook is called every time the component renders.

As you have registered onmousemove inside useEffect, the handleMouseMove function is called after rendering of component.

CodePudding user response:

useEffect runs every time a dependency changes, but as you've only provided [] it will run once and create your listener.

You can also remove the listener when the component is unmounted by returning a callback function. For example

  useEffect(() => {
    window.addEventListener("onmousemove", handleMouseMove);

    return () => {
        window.removeEventListener("onmousemove", handleMouseMove);
    }
  }, []);
  • Related