Last active
September 14, 2024 00:22
-
-
Save dwhiteGUK/4dbf525b44510a5f9620ad3cb6693a37 to your computer and use it in GitHub Desktop.
Hooks
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
import { useEffect, useState } from 'react'; | |
const useDebounce = (value, delay = 500) => { | |
// State and setters fpr debounced value | |
const [debouncedValue, setDebouncedValue] = useState(value); | |
useEffect(() => { | |
const handler = setTimeout(() => { | |
setDebouncedValue(value); | |
}, delay); | |
return () => { | |
clearTimeout(handler); | |
}; | |
}, [value, delay]); | |
return debouncedValue; | |
}; | |
export default useDebounce; |
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
/* | |
* https://medium.com/the-non-traditional-developer/how-to-use-an-intersectionobserver-in-a-react-hook-9fb061ac6cb5 | |
*/ | |
import { useEffect, useRef, useState } from 'react'; | |
const useIntersect = (({ root = null, rootMargin, threshold = 0 }) => { | |
const [entry, setEntry] = useState({}); | |
const [node, setNode] = useState(null); | |
const observer = useRef(null); | |
useEffect(() => { | |
if (observer.current) observer.current.disconnect(); | |
observer.current = new IntersectionObserver( | |
([entry]) => setEntry(entry), | |
{ | |
root, | |
rootMargin, | |
threshold, | |
}, | |
); | |
const { current: currentObserver } = observer; | |
if (node) currentObserver.observe(node); | |
return () => currentObserver.disconnect(); | |
}, [node, root, rootMargin, threshold]); | |
return [setNode, entry]; | |
}); | |
export default useIntersect; |
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
const useScrollToItem = (event) => { | |
const element = document.getElementById(event.target.value); | |
window.scrollTo({ | |
top: Math.floor(element.offsetTop), | |
left: 0, | |
behavior: 'smooth', | |
}); | |
}; | |
export default useScrollToItem; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment