Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG]removeEventListener will not work properly. #12

Open
ritwickdey opened this issue Jul 26, 2019 · 0 comments · May be fixed by #13
Open

[BUG]removeEventListener will not work properly. #12

ritwickdey opened this issue Jul 26, 2019 · 0 comments · May be fixed by #13

Comments

@ritwickdey
Copy link

ritwickdey commented Jul 26, 2019

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);
};
}, []);

@ritwickdey ritwickdey changed the title Bugs in the code. removeEventListener will not work properly. [BUG]removeEventListener will not work properly. Jul 26, 2019
ritwickdey added a commit to ritwickdey/online-status that referenced this issue Jul 26, 2019
@ritwickdey ritwickdey linked a pull request Jul 26, 2019 that will close this issue
ritwickdey added a commit to ritwickdey/online-status that referenced this issue Jul 26, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant