Skip to content

Instantly share code, notes, and snippets.

@dwhiteGUK
Last active May 20, 2020 10:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dwhiteGUK/4dbf525b44510a5f9620ad3cb6693a37 to your computer and use it in GitHub Desktop.
Hooks
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;
/*
* 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;
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