I'm using the following useEffect in a component to control active state on an anchor side navigation for the page.
const [activeIndex, setActiveIndex] = useState(0);
useEffect(() => {
const handleScroll = (e: Event) => {
var index = nearestIndex(
window.scrollY,
Anchors,
0,
Anchors.length - 1
);
setActiveIndex(index);
}
document.addEventListener("scroll", handleScroll);
return () => {
document.removeEventListener("scroll", handleScroll);
}
}, [Anchors]);
When I navigate to another page using next/link the scroll event listener is firing and then being removed. This is causing an error inside nearestIndex because the refs inside Anchors are now null.
EDIT: Component/Page Flow Explanation
scroll event listener fires throwing an error, listener is then removedscroll event listener is no longer registered