Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if React app is being viewed on Desktop or Mobile

Making a React App and need to have different functionality for Desktop and Mobile. So far I did this:

const [width, setWidth] = useState(window.innerWidth);
const [mobile, setMobile] = useState(false);

const handleWindowSizeChange = () => {
        setWidth(window.innerWidth);
        if(width <= 500) {
            setMobile(true);
        } else setMobile(false);
    }

    useEffect(() => {
        window.addEventListener('resize', handleWindowSizeChange);
        return () => {
            window.removeEventListener('resize', handleWindowSizeChange);
        }
    }, []);

But it’s not working. I console logged the "mobile" state and it always logs "false" even tho i change the screen size in my browser. Especially if i reload my page while still being in mobile view. How do I make it work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It looks like there are two issues preventing this from working.

  1. You’re not setting isMobile to the correct value on initial page load. The handler looks reasonable for updating isMobile on resize, but if the window isn’t resized, it won’t be set correctly.
  2. Within handleWindowSizeChange, you’re using width, which hasn’t been set to window.innerWidth yet.

My recommendation would be to get rid of the width state (unless you need it outside of getting isMobile). Your code could look something like:

const [mobile, setMobile] = useState(window.innerWidth <= 500);

const handleWindowSizeChange = () => {
  setMobile(window.innerWidth <= 500);
}

useEffect(() => {
  window.addEventListener('resize', handleWindowSizeChange);
  return () => {
    window.removeEventListener('resize', handleWindowSizeChange);
  }
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading