Sobes.tech
Junior — Senior

Refactoring the ClickListener component in React

livecode

Task condition

It is necessary to improve the implementation of the ClickListener component by eliminating potential dependency issues with hooks and optimizing event handling.

import React from "react";

const Service = {
    send: (data) => console.log(data + " uploaded"),
};

const ClickListener = () => {
    const [coordinate, setCoordinate] = React.useState();
    const handleUpload = React.useCallback(() => {
        Service.send(coordinate);
    }, [coordinate]);

    React.useEffect(() => {
        const onClick = (e) => {
            setCoordinate(e.pageX);
            handleUpload();
        };
        document.addEventListener("click", onClick);
        return () => document.removeEventListener("click", onClick);
    }, [handleUpload]);

    return <>{coordinate}</>;
};