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

Removing event listener #41

Closed
lsbyerley opened this issue Mar 11, 2021 · 2 comments
Closed

Removing event listener #41

lsbyerley opened this issue Mar 11, 2021 · 2 comments

Comments

@lsbyerley
Copy link

Thanks for the awesome hook!

Apologies if this is obvious but how would you remove the event listener? Let's say i'm attaching it based on the value of another variable..

if (editState === 'haschanges) {
  useEventListenter('beforeunload', handler);
} else {
  // remove the listener
}
@iamaamir
Copy link

may be passing the condition to the hook for removing .

useEventListenter('beforeunload', handler,  editState === 'haschanges');

or may be simply passing handler as null

useEventListenter('beforeunload', editState === 'haschanges' ? handler : null);

@MarkMYoung
Copy link

I think the cleanest way is for useEventListenter to return an object with a reference to the "cleanup" function, possibly called remove.

  const cleanupRef = useRef();
...
  useEffect(() => {
...
    cleanupRef.current = () => {
      element.removeEventListener(eventName, eventListener, opts);
    };
    return cleanupRef.current;
  }, [eventName, element, capture, passive, once]);
  return { remove: cleanupRef };
};

I'm not sure about returning a useRef vs. its current value, but you get the idea.

const { remove: removeClickHandler } = useEventListener('click', ...);

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

No branches or pull requests

3 participants