Skip to content

Add custom hook for using event listeners #15

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions hooks/useEventListener.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { useRef, useEffect } from "react";

/*
Hook for using event listeners

Example:
const handler = useCallback((e) => console.log(`X: ${e.clientX} Y: ${e.clientY}`), []);

useEventListener('click', handler);

NOTE! If you dont use 'useCallback' hook, the handler will change every render
*/

const useEventListener = (eventName, handler) => {
const handlerRef = useRef();

useEffect(() => {
handlerRef.current = handler;
}, [handler]); // if the handler function changes get new reference

useEffect(
() => {
const currentHandler = (event) => handlerRef.current(event);
document.addEventListener(eventName, currentHandler);

return () => {
document.removeEventListener(eventName, currentHandler);
};
},
[eventName] // Re-run if eventName changes
);
};

export default useEventListener;