My webpage has a scroll event listener, which detects where the user is on the page. Basically, this functionality is to enlarge a nav bar or not.
The event listener is straightforward, and looks like this:
MyComponent.jsx
const MyComponent = () => {
const { setWindowHeight } = useContext(AppContext);
const handleScroll = useCallback(
(div) => {
setWindowHeight(div.scrollTop) // the set state is coming from a context provider shared across the app
},
[]
);
// Attach the scroll listener to the div
useEffect(() => {
const scrollableElement =
document.getElementsByClassName('scrollItem')[0];
scrollableElement.addEventListener('scroll', () => handleScroll(scrollableElement));
}
}, [handleScroll]);
return (
// The component
)
}
NavBar.jsx
const NavBar = () => {
const { windowHeight } = useContext(AppContext);
return (
<div style={{minHeight: windowHeight > 0 ? '5vh' : '20vh'}}>
// The navbar
</div>
)
}
However, my problem is that this has slowed down my page quite a bit, and every scroll seems to lag, presumably because there is a re-render on every scroll to figure out where the user is on the page.
Is there a better way to optimize this?