Skip to content

Instantly share code, notes, and snippets.

@JayMGurav
Last active May 2, 2021 04:00
Show Gist options
  • Save JayMGurav/2c24d35e1ea5893f7d7bd78d7fb4707b to your computer and use it in GitHub Desktop.
Save JayMGurav/2c24d35e1ea5893f7d7bd78d7fb4707b to your computer and use it in GitHub Desktop.
A custom scroll-to-top hook
import { useEffect, useState } from "react";
export default function scrollToTop(){
const [isBtnVisible, setIsBtnVisible] = useState(false);
const [pageYOffset, setPageYOffset] = useState(0);
useEffect(()=>{
const checkVisiblity = () => {
setPageYOffset(window.pageYOffset);
if(pageYOffset > window.innerHeight){
setIsBtnVisible(true);
}else{
setIsBtnVisible(false);
}
}
window.addEventListener('scroll', checkVisiblity);
return () => window.removeEventListener('scroll', checkVisiblity);
},[pageYOffset]);
const scrollToTop = () => {
if(window && isVisible){
window.scrollTo({
top: 0,
behavior:"smooth"
});
}
}
return [isBtnVisible, scrollToTop];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment