I'm working on creating a custom hook that captures the browser window size to let me know if it's mobile or not. At the moment, my issue is React telling me it can't retain the variable value of screenSize within the useEffect hook. How do I get around this?
export default function useIsMobile() {
let screenSize = 0;
useEffect(() => {
window.addEventListener("resize", () => {
screenSize = window.innerWidth;
});
return () => {
window.removeEventListener("resize", () => {
screenSize = window.innerWidth;
})
}
}, [screenSize]);
return screenSize <= 768;
}
You can use the useRef hook to create a variable on the component level, then use the .current property to update it's value.
export default function useIsMobile() {
const screenSize = useRef();
useEffect(() => {
window.addEventListener("resize", () => {
screenSize.current = window.innerWidth;
});
return () => {
window.removeEventListener("resize", () => {
screenSize.current = window.innerWidth;
})
}
}, []);
return screenSize.current <= 768;
}
Note that I also removed the dependency from the useEffect hook because it's not needed. Because it's a ref and not a state, you will use the same variable every time which means that you don't need to re-register the listener.
UPDATE
The way useRef work will not trigger a re-render which is why there is a need to use a useState hook instead.
This code snippet will cause a re-render every time the mode changes.
const getIsMobile = () => window.innerWidth <= 768;
export default function useIsMobile() {
const [isMobile, setIsMobile] = useState(getIsMobile());
useEffect(() => {
const onResize = () => {
setIsMobile(getIsMobile());
}
window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
}
}, []);
return isMobile;
}
Note that I moved getIsMobile outside the component because it doesn't contain any logic related to it and also so it could be called on the default value of the useState hook to save a re-render right when the hook first loads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With