Home > Enterprise >  React/JS gets stuck: weird bug I can't solve
React/JS gets stuck: weird bug I can't solve

Time:11-21

I am a beginner with React, JS, and I wrote a simple, ten-line program that tracks clicks in a web document and displays their positions in a text element.

It seems simple, and it works as intended, but only for seven clicks, after which the program locks up and will not execute any more, and won't display the positions of new clicks, and the page will not even update.

This exact thing happens whether I run it from my local Chrome and Safari or if I run it inside an online sandbox.

What could be causing this issue? How should I diagnose this kind of an issue?

Here is the code:

import "./styles.css";
import React from "react";
import { useState } from "react";

export default function App() {
  const [coordinates, setCoordinates] = useState({ x: 1, y: 1 });

  function handleClick(e) {
    setCoordinates({ x: e.screenX, y: e.screenY });
  }
  document.addEventListener("click", handleClick);

  return (
    <p>
      x: {coordinates.x}, y: {coordinates.y};
    </p>
  );
}

The sandbox with code is Edit lucid-tamas-yr3zvs

CodePudding user response:

Try wrapping the document.addEventListener() inside a useEffect with empty dependency array.

useEffect(() => {
  document.addEventListener("click", handleClick);
}, [])

That way, you only invoke the addEventListener once (at component mount) and not every time the component re-renders.

  • Related