Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
Not receiving current state within setInterval

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!