Im trying to get the current state within the setInterval function, which isn’t working. I’m only getting the default value. I think it has to do something with the useEffect that only loads on mount.
const [liveMouse, setLiveMouse] = useState({
currentX: 0,
currentY: 0,
lastX: 0,
lastY: 0
});
useEffect(() => {
let mounted = true;
if (mounted) {
document.addEventListener("mousemove", (event) => {
setLiveMouse(previousMouse => ({...previousMouse, currentX: event.clientX, currentY: event.clientY }));
})
const mouseCheckInterval = setInterval(() => {
// Not getting the current state, only the default value
if (liveMouse.currentX !== liveMouse.lastX || liveMouse.currentY !== liveMouse.lastY) {
setLiveMouse(previousMouse => ({...previousMouse, lastX: liveMouse.currentX, lastY: liveMouse.currentY }))
}
}
return (() => {
mounted = false;
clearInterval(mouseCheckInterval)
}
}, [])
How can I fix this problem?