From 3d2cc1c89d9c460e4cf5a3824b4fe0389e08341a Mon Sep 17 00:00:00 2001 From: William Tran Date: Wed, 7 Jul 2021 18:06:30 -0400 Subject: [PATCH] Fix debounce and add navbar --- components/OrganizedContent.tsx | 54 ++++++++++++++++----------------- pages/_app.tsx | 2 +- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/components/OrganizedContent.tsx b/components/OrganizedContent.tsx index 528e2689..a558b141 100644 --- a/components/OrganizedContent.tsx +++ b/components/OrganizedContent.tsx @@ -4,6 +4,7 @@ import React, { useState, useRef, useEffect, + useCallback, } from "react"; import styles from "./OrganizedContent.module.css"; @@ -194,27 +195,26 @@ interface BurgerProps { const Burger = ({ open, setOpen, componentIsVisible }: BurgerProps) => { const [prevScrollPos, setPrevScrollPos] = useState(0); const [burgerVisible, setBurgerVisible] = useState(true); - const debouncedPrevScrollPos = useDebounce(prevScrollPos, 100); + + const handleScroll = useDebounce(() => { + // find current scroll position + const currentScrollPos = window.pageYOffset; + setBurgerVisible( + componentIsVisible && + ((prevScrollPos > currentScrollPos && + prevScrollPos - currentScrollPos > 70) || + currentScrollPos < 10) + ); + + // set state to new scroll position + setPrevScrollPos(currentScrollPos); + }); useEffect(() => { - const handleScroll = () => { - // find current scroll position - const currentScrollPos = window.pageYOffset; - // set state based on location info (explained in more detail below) - setBurgerVisible( - componentIsVisible && - ((debouncedPrevScrollPos > currentScrollPos && - debouncedPrevScrollPos - currentScrollPos > 70) || - currentScrollPos < 10) - ); - - // set state to new scroll position - setPrevScrollPos(currentScrollPos); - }; window.addEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll); - }, [componentIsVisible, debouncedPrevScrollPos, burgerVisible]); + }, [handleScroll]); return (
(value: T, delay?: number): T { - const [debouncedValue, setDebouncedValue] = useState(value); +function useDebounce(func: () => void, delay = 300) { + const timerRef = useRef(undefined); + return useCallback(() => { + if (timerRef.current != null) { + return; + } - useEffect(() => { - const timer = setTimeout(() => setDebouncedValue(value), delay || 500); - - return () => { - clearTimeout(timer); - }; - }, [value, delay]); - - return debouncedValue; + timerRef.current = window.setTimeout(() => { + func(); + timerRef.current = undefined; + }, delay); + }, [func, delay]); } function createSections(sections: Section[]) { diff --git a/pages/_app.tsx b/pages/_app.tsx index 3fde19fd..f897db09 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -18,7 +18,7 @@ export default function App({ Component, pageProps }: AppProps): JSX.Element {
- {/* mobile OrganizedContent doesnt like non-mobile navbar*/} + {/* Wrapping content with a div to allow for a display: block parent */}