Despite considering my self a seasoned programmer and being developing for over 15 years, I’m surprised I didn’t know about the ownerDocument.defaultView property.
I basically returns the window object (or null) associated with a specific DOM node. It could be used to safely attach an event listener to a window object from a component that is rendered outside the main window where the application was initially rendered (think portals).
function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
const ref = useRef(null);
useEffect(() => {
const win = ref.current?.ownerDocument.defaultView || window;
const toggle = (e) => {
if (e.metaKey && e.key === "d") {
e.preventDefault();
setTheme((t) => (t === "dark" ? "light" : "dark"));
}
};
win.addEventListener("keydown", toggle);
return () => win.removeEventListener("keydown", toggle);
}, []);
return (
<div ref={ref} className={theme}>
{children}
</div>
);
}
From the same article, also learned about useId and cache 😛
Reference: https://shud.in/thoughts/build-bulletproof-react-components, great article btw! 💯