From 7baef539fdefe003769eb431a8ee35c10be02a1d Mon Sep 17 00:00:00 2001 From: developomp Date: Wed, 19 Jan 2022 14:04:17 +0900 Subject: [PATCH] read progress update - update progress on page height change - make use of useCallback --- source/src/components/Navbar.tsx | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/source/src/components/Navbar.tsx b/source/src/components/Navbar.tsx index 514437b..05a6948 100644 --- a/source/src/components/Navbar.tsx +++ b/source/src/components/Navbar.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react" +import { useCallback, useEffect, useState } from "react" import styled from "styled-components" import { Link, useLocation } from "react-router-dom" import ReactTooltip from "react-tooltip" @@ -86,14 +86,20 @@ const ReadProgress = () => { const location = useLocation() // https://stackoverflow.com/a/8028584/12979111 - function scrollHandler() { + const scrollHandler = useCallback(() => { setScroll(((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100) - } + }, []) useEffect(() => { + const resizeObserver = new ResizeObserver(() => { + scrollHandler() + }) + + resizeObserver.observe(document.body) window.addEventListener("scroll", scrollHandler) return () => { + resizeObserver.disconnect() window.removeEventListener("scroll", scrollHandler) } }, [])