Created
April 9, 2021 05:50
-
-
Save qvil/56349bc2a7981c4ad173aae6341ed205 to your computer and use it in GitHub Desktop.
Check sticky with offset
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 { useState, useEffect, Dispatch, SetStateAction } from "react"; | |
interface UseStickyReturnType { | |
isSticky: boolean; | |
setIsSticky: Dispatch<SetStateAction<boolean>>; | |
} | |
/** | |
* @description Check sticky with offset | |
* @param offset | |
* @example | |
* const menuHeight = 50 | |
* const { isSticky } = useSticky(menuHeight) | |
* @returns {UseStickyReturnType} | |
*/ | |
const useSticky = (offset: number): UseStickyReturnType => { | |
const [isSticky, setIsSticky] = useState(false); | |
const handleScroll = () => { | |
if (window.pageYOffset > offset) { | |
setIsSticky(true); | |
} else { | |
setIsSticky(false); | |
} | |
}; | |
useEffect(() => { | |
window.addEventListener("scroll", handleScroll); | |
return window.addEventListener("scroll", handleScroll); | |
}, []); | |
return { isSticky, setIsSticky }; | |
}; | |
export default useSticky; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment