DEV Community

Discussion on: How to Create a Custom useDeviceDetect() React Hook

larsejaas profile image
Lars Ejaas

This was really helpful - thanks! I used to check if navigator.maxTouchPoints > 0 - this way I assumed that all touch devices was mobile devices, but after more and more laptops comes with touchscreens this was a bad solution!

I made a small change to your custom hook. I did not like how the function returns false on mobile devices until the function is resolved. So I have set the initial state to undefined.
This way I can do "if(isMobile === undefined) return" inside useEffect hooks in other components. I use this for things like animations I only run on mobile devices etc. Then i just place [isMobile] as a dependency in the useEffect hook - and the useEffect hook will be reevaluated when the isMobile returns true or false :-)