0

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>}

2
  • I usually handle these usecases with css media queries. it's faster and avoids extra rerenders. Commented Apr 15, 2024 at 12:55
  • Yes that's right. The only reason why I prefer this approach is that the element is completely removed from the DOM this way. Commented Apr 15, 2024 at 14:30

1 Answer 1

0

Try this one

  useEffect(() => {
    let timeoutId;

    const handleResize = () => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
            setWindowWidth(window.innerWidth);
        }, 100); // Adjust the debounce delay as needed
    };

    window.addEventListener("resize", handleResize);

    handleResize();

    return () => {
        window.removeEventListener("resize", handleResize);
        clearTimeout(timeoutId); // Cleanup
    };
}, []);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.