Skip to content

[BUG]removeEventListener will not work properly. #12

@ritwickdey

Description

@ritwickdey

Every-time when state will update, goOnline and goOffline will get re-defined (means, new memory location - different reference).

When the hook will run for first time, addEventListener will attach first reference of the goOnline or goOffline. And then when the state will update, we will get new reference of goOnline and goOffline. so, we need to move the 2 functions inside of useEffect, so that it'll not be redefined again and again.

function useOnlineStatus() {
const [onlineStatus, setOnlineStatus] = useState(getOnlineStatus());
const goOnline = () => setOnlineStatus(true);
const goOffline = () => setOnlineStatus(false);
useEffect(() => {
window.addEventListener("online", goOnline);
window.addEventListener("offline", goOffline);
return () => {
window.removeEventListener("online", goOnline);
window.removeEventListener("offline", goOffline);
};
}, []);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions