[components/MDX][s]: minor changes - observer hook

This commit is contained in:
olayway 2022-06-06 18:34:13 +02:00
parent 706c7b0d02
commit cc74f3a892
2 changed files with 16 additions and 15 deletions

View File

@ -26,6 +26,4 @@ const MdxContent = ({ body }) => {
return <Component components={customComponents} />;
};
// prevent rerendering of the component if it's props don't change
// i.e. re-render only when the observer is set
export default React.memo(MdxContent);
export default MdxContent;

View File

@ -1,5 +1,4 @@
import { useState, useEffect } from 'react';
import { useState, useEffect } from "react";
/* Creates an Intersection Observer to keep track of headings intersecting
* a section of the viewport defined by the rootMargin */
@ -13,7 +12,7 @@ const getIntersectionObserver = (callback) => {
{
root: null,
threshold: 0.55,
rootMargin: "-65px 0% -85% 0%" // 65px is a navbar height
rootMargin: "-65px 0% -85% 0%", // 65px is a navbar height
}
);
};
@ -24,7 +23,7 @@ const useHeadingsObserver = () => {
/* Runs only after the first render, in order to preserve the observer
* between component rerenderings (e.g. after activeHeading change). */
useEffect((() => {
useEffect(() => {
const observer = getIntersectionObserver((entry) => {
if (entry.isIntersecting) {
setActiveHeading(entry.target.id);
@ -32,26 +31,30 @@ const useHeadingsObserver = () => {
});
setObserver(observer);
return observer.disconnect();
}), [])
return () => {
observer.disconnect();
};
}, []);
/* On initial render activeHeading will be `null`, since the observer
* has not been instantiated yet. However, we still want to highlight
* the current heading in the ToC based on the current url. */
useEffect(() => {
if (!activeHeading) {
return
return;
}
const tocLink = document.querySelector(`.toc-link[href="#${activeHeading}"]`)
const tocLink = document.querySelector(
`.toc-link[href="#${activeHeading}"]`
);
tocLink.classList.add("active");
return () => {
tocLink.classList.remove("active")
}
}, [activeHeading])
tocLink.classList.remove("active");
};
}, [activeHeading]);
return observer;
}
};
export default useHeadingsObserver;