I'm using a custom hook to render different elements on the page based on the screen size.
Hovewer during rendering there is a delay because of the useEffect hook. Elements that are rendered conditionally only appear after a few milisec or 1 sec delay.
Is it expected or is there a better way to achive the same result?
const useMobile = () => {
const [windowWidth, setWindowWidth] = useState<number | undefined>(undefined);
useEffect(() => {
const handleResize = () => {
setWindowWidth(window.innerWidth)
};
window.addEventListener("resize", handleResize);
handleResize();
return () => window.removeEventListener("resize", handleResize);
}, [])
if (!windowWidth) return false;
return windowWidth <= 860;
}
I'm using this custom hook, and I would like to minimalize this delay.
Conditional rendering part:
const isSmallScreen = useMobile();
...
{isSmallScreen && <button onClick={toggleOpen}>NavTrigger</button>}