This repository has been archived by the owner on Jun 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(Hooks): New useEventListener hook
- Loading branch information
1 parent
0d0b1dd
commit b3ea602
Showing
3 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
--- | ||
name: useEventListener | ||
menu: Hooks | ||
--- | ||
|
||
# useEventListener | ||
|
||
A simple hook that adds a global event listener & cleans up after it when the component unmounts. | ||
|
||
By default, the event listener is added on `document`, but you can change the element by passing a custom target element to it as the third parameter. | ||
|
||
## Examples | ||
|
||
```js | ||
useEventListener('click', onBodyClick); | ||
``` | ||
|
||
```js | ||
useEventListener('scroll', onScroll, scrollContainerRef.current); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import {useEffect, useRef} from 'react'; | ||
|
||
function useEventListener(eventName, callback, element = document) { | ||
const callbackRef = useRef(callback); | ||
|
||
useEffect(() => { | ||
callbackRef.current = callback; | ||
}, [callback]); | ||
|
||
useEffect(() => { | ||
const currentCallback = callbackRef.current; | ||
|
||
element.addEventListener(eventName, currentCallback); | ||
|
||
return function cleanUp() { | ||
element.removeEventListener(eventName, currentCallback); | ||
}; | ||
}, [eventName, element]); | ||
} | ||
|
||
export default useEventListener; |