From 327feeb3ab1926159f3b4acea13c9e483dff99c7 Mon Sep 17 00:00:00 2001 From: Shariq Date: Thu, 10 Oct 2024 02:20:09 +0530 Subject: [PATCH] fix(scroll): fix Optimisation --- components/basic/MoveToTop.js | 40 +++++++++++++++-------------------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/components/basic/MoveToTop.js b/components/basic/MoveToTop.js index ee5c909a..1ce17288 100644 --- a/components/basic/MoveToTop.js +++ b/components/basic/MoveToTop.js @@ -1,47 +1,41 @@ -import React, { useState } from "react"; +import React, { useEffect, useState } from "react"; import { FaArrowCircleUp } from "react-icons/fa"; const ScrollButton = () => { - const [visible, setVisible] = useState(false); + const [isVisible, setIsVisible] = useState(false); - const toggleVisible = () => { - const scrolled = document.documentElement.scrollTop; - const topBtn = document.getElementById("top-btn"); - if (scrolled > 300) { - setVisible(true); - topBtn.classList.add("tw-opacity-100"); - } else if (scrolled <= 300) { - topBtn.classList.remove("tw-opacity-100"); - setTimeout(() => { - setVisible(false); - }, 100); - } - }; + useEffect(() => { + const handleScroll = () => { + setIsVisible(window.scrollY > 300); + }; + window.addEventListener("scroll", handleScroll); + return () => { + window.removeEventListener("scroll", handleScroll); + }; + }, []); const scrollToTop = () => { - const scrollDuration = 500; - const scrollStep = -window.scrollY / (scrollDuration / 15); + const scrollStep = -window.scrollY / 15; const scrollInterval = setInterval(() => { if (window.scrollY === 0) { - clearInterval(scrollInterval); + clearInterval(scrollInterval); } else { - window.scrollBy(0, scrollStep); + window.scrollBy(0, scrollStep); } }, 15); }; - window.addEventListener("scroll", toggleVisible); - return (
);