Can someone please why can I not attach an event listener to window object in nextjs? When I try 'resize' event, everything works fine, but with 'load' event it seems 'load' event is not recognized'
import { useEffect } from "react";
export default function Home() {
useEffect(() => {
window.addEventListener("load", (e) => console.log(e));
});
return <div>Hello world</div>;
}
The problem is that the page has already loaded when this code begins to run. I'm not sure what you're trying to achieve, but from what i see it can be done with just the useEffect hook.
You can verify what i just said by running this snippet :
const handler = (e) => console.log(e, "here");
useEffect(() => {
if (document.readyState === "complete") {
handler();
} else {
window.addEventListener("load", handler);
return () => document.removeEventListener("load", handler);
}
}, []);
Also I have to note that this is not nextJs specific, this is just react.