https://codesandbox.io/s/compassionate-wilbur-6r1c3y?file=/src/App.tsx:0-1366
Can anyone explain why this line is not working?
"window.removeEventListener("mousemove", tellPos, false);"
I can see that the function is getting called in the console so I assume its not as easy as it seems to remove event listeners.
import { useState } from "react";
import "./styles.css";
export default function App() {
let [page, setPage] = useState({ pageX: 50, pageY: 50 });
let [string, setString] = useState(
"Position X : " + page.pageX + " Position Y : " + page.pageY
);
function tellPos(p: any) {
let page2: any = {};
page2.pageX = p.pageX - 50;
page2.pageY = p.pageY - 10;
setPage(page2);
setString("Position X : " + p.pageX + " Position Y : " + p.pageY);
}
function addListeners() {
console.log("fire add");
window.addEventListener("mousemove", tellPos, false);
}
function removeListeners() {
console.log("fire remove");
window.removeEventListener("mousemove", tellPos, false);
}
// let style = {position:"absolute", top:page.pageY+"px", left:page.pageX+"px"}
return (
<div
onClick={() => {
removeListeners();
}}
className="App"
>
<div
style={{
border: "1px solid black",
position: "absolute",
top: page.pageY + "px",
left: page.pageX + "px"
}}
onMouseEnter={() => {
addListeners();
}}
onClick={() => {
removeListeners();
}}
>
<h1>hover to move me</h1>
{string}
</div>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
I think I see the problem here:
Upon binding tellPos to mousemove, you're triggering a re-render (i.e: a re-execution of your App function) whenever the mouse is moved (because tellPos triggers a state update, which triggers the re-render). Because tellPos, addListeners and removeListeners are defined each time during render, removeListeners is being instructed to remove an event handler matching a new instance of tellPos from window, leaving the old one that was bound during the initial addListeners intact.
The solution to this problem appears to be avoiding the definition of functions during render, especially when those functions are being bound as event listeners to elements that aren't being replaced in subsequent renders.
I've got a crude demo with tellPos stored outside of the render function, showing this functionality seemingly behaving as expected: https://codesandbox.io/s/crimson-waterfall-xuzlb9?file=/src/App.tsx