Home > database >  How to add device (isMobile) specific code to an SSG page in NextJS?
How to add device (isMobile) specific code to an SSG page in NextJS?

Time:09-09

I have a NextJS app page that should be SSG. I'll fetch all the data that it needs during build time.

But a small part of the code (social media share link) needs information about the device of the user. Basically, I want to know whether I'm on desktop or mobile.

What is the recommended approach for that scenario?

Should I render one of the two possibilities on build time and add some client useEffect code to detect and change it if necessary?

CodePudding user response:

To check whether you are on desktop or mobile you can use some library like react-device-detect, react-responsive

Or if you are using material-UI then you can use useMediaQuery with theme.breakpoints.

Or you can use the traditional way navigator.userAgent.

CodePudding user response:

Yes, I believe that regardless of what strategy you use to detect what device you are on (or screen size if you need to sync with css media queries), you should render a default option and then inside of a useEffect call you can update state to determine which option should end up in the DOM.

You just want to make sure that the default state is not based on data that can only be determined in the browser or else you will likely end up with a hydration error.

  • Related