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?
It looks like there are two issues preventing this from working.
isMobileto 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.handleWindowSizeChange, you're usingwidth, which hasn't been set towindow.innerWidthyet.My recommendation would be to get rid of the
widthstate (unless you need it outside of gettingisMobile). Your code could look something like: