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

156
Views
Save mouse position in a state with react

I need to save the mouse position in an array for an application, but the positions doesn't save in the array, it just replace it and I don't know why, someone help please. Here is the code:

const mouseXY = async e =>{
    setCoords([...coords,{
      x:e.clientX,
      y:e.clientY
    }])
  }

useEffect(()=>{
    let interval = null;
    interval = setInterval(() => {
      setTime((prevTime) => prevTime + 0.5);
    }, 1000);

    window.addEventListener('mousemove', mouseXY);
}

When I print I get this:

[{x: 379, y: 106}]

A single element in an Array. What I want to get would be something like this:

[{x: 379, y: 106},
{x: 379, y: 106},
{x: 379, y: 106},
{x: 379, y: 106},
{x: 379, y: 106},
{x: 379, y: 106},
{x: 379, y: 106}]

with the position of the mouse around the page.

almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

It is because of staleState. coords was an empty array at the time that mouseXy was defined and handed to addEventListener, and it will always be an empty array.

Instead, update your setCoords call to use the callback pattern.

const mouseXY = (e) => {
  setCoords((prevState) => [...prevState, { x: e.clientX, y: e.clientY }]);
};
almost 4 years ago · Santiago Trujillo Report
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!