I have a hook implemented, which determines the currently active (in view) section according to the scroll position. The final result can be viewed in the NavBar of https://mwskwong.com.
Now I use both throttle on the scroll event to prevent it from being called too often and startTransition because this is an unimportant UI update. My question is, is this necessary? Can I just use startTransition?
The following is the full code of my hook.
const useActiveSectionId = () => {
const [, startTransition] = useTransition();
const [activeSectionId, setActiveSectionId] = useState(HOME.id);
const isScrollToBottom = () => window.innerHeight + window.scrollY >= document.body.offsetHeight;
const isSectionActive = section => section
&& section.offsetTop < document.documentElement.scrollTop
+ document.documentElement.clientHeight / 8;
useEffect(() => {
const initId = window.location.hash?.slice(1);
if (initId) setActiveSectionId(initId);
const sectionIds = Object.values(nav).map(({ id }) => id).reverse();
const handleScroll = throttle(() => {
if (isScrollToBottom()) {
startTransition(() => setActiveSectionId(sectionIds[0]));
} else {
for (const sectionId of sectionIds) {
const section = document.getElementById(sectionId);
if (isSectionActive(section)) {
startTransition(() => setActiveSectionId(sectionId));
break;
}
}
}
}, 16);
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
return activeSectionId;
};