score:3

Accepted answer

the way i understood the question is that, you want to stop tracking the mouse movement.

if my understanding is correct, you can pass a flag to start/top tracking the mouse movement.

this demo shows that you can turn on/off the mouse tracking and

you can follow along edit so.answer.56777009

demo

you can simply pass a variable, which you can check within your useeffect.

function usemouseposition(shouldtrack = true) {
  let [mouseposition, setmouseposition] = usestate({
    x: null,
    y: null
  });

  function handlemousemove(e) {
    setmouseposition({
      x: e.pagex,
      y: e.pagey
    });
  }

  useeffect(() => {
    if (!shouldtrack) return;

    window.addeventlistener("mousemove", handlemousemove);
    return () => {
      window.removeeventlistener("mousemove", handlemousemove);
    };
  }, [shouldtrack]);

  return mouseposition;
}

function app() {
  const [usemouse, setusemouse] = usestate(true);
  let { x, y } = usemouseposition(usemouse);

  useeffect(() => {
    console.log(`x, y`, x, y);
  }, [x, y]);

  return (
    <div classname="app">
      <h1>hello codesandbox</h1>
      <h2>start editing to see some magic happen!</h2>
      <button onclick={() => setusemouse(_ => !_)}>
        tracking mouse movement is {usemouse ? "on" : "off"}
      </button>
    </div>
  );
}

clicking on the button toggles the track status.

and for "removing the hook", you can't as it's embedded in your function component. you can at least prevent the "side effect" from running using a condition.

⚠ note that useeffect has a dependency as [shouldtrack].

score:0

you need to specify conditions in handlemousemove

in the next solution, you stop render outside the pink border and remove the listener under the black line.

note: added usecallback and dep array because of unnecessary renderings.

enter image description here

const isinsidebox = ({ pagex, pagey }) =>
  left <= pagex && pagex <= right && top <= pagey;

function usemouseposition() {
  let [mouseposition, setmouseposition] = usestate({
    x: null,
    y: null
  });

  const handlemousemove = usecallback(
    e => {
      isinsidebox(e) &&                     // add condition for border
        setmouseposition({
          x: e.pagex,
          y: e.pagey
        });

      e.pagey >= bottom &&                  // add condition for black line
        window.removeeventlistener("mousemove", handlemousemove);
    },
    [setmouseposition]
  );

  useeffect(() => {
    window.addeventlistener("mousemove", handlemousemove);
    return () => {
      window.removeeventlistener("mousemove", handlemousemove);
    };
  }, [handlemousemove]);

  return mouseposition;
}

Related Query

More Query from same tag