use-breakpoint icon indicating copy to clipboard operation
use-breakpoint copied to clipboard

Add support for server side rendering

Open MatiMenich opened this issue 5 years ago • 2 comments

Hi! I'm trying to use this library for a Gatsby project, but when I try to build it for production, it fails because the window object is undefined.

2020-09-10T13:24:12.621Z [WARNING]: error "window" is not available during server side rendering.
2020-09-10T13:24:12.641Z [INFO]: 11 |     isLandscape,
                                 12 |     isPortrait: !isLandscape,
                                 > 13 |     isHDPI: window.devicePixelRatio > 1,
                                 | ^
                                 14 |     innerWidth: iw,
                                 15 |     innerHeight: ih,
                                 16 |     media: {}
...

Adding support for SSR would be great, thanks!

MatiMenich avatar Sep 10 '20 14:09 MatiMenich

Hi, thanks for opening the issue. Any suggestion what it should do in case of SSR. The thing is on server side we don't know the nature of the client: window size, DPI, etc. What strategy we should use for this case? During re-hydration you may end up with a completely different markup then what you need.

wintercounter avatar Sep 10 '20 15:09 wintercounter

I went and checked other libraries how they deal with this case, but non of those strategies are suitable for us. It's either providing some guessed data and does conditional rendering, all it's only about rendering and it renders every possible outcome and simply hides the ones not needed. use-breakpoint is about value, not just rendering.

I think the closest we can get to this is returning the default value in ssr environment.

One more feature I can add is having an "ssr breakpoint" so you can define what value you want to use in case of ssr (if it's other than default).

const value = useBreakpoint(1, ['mobile', 2]) // 1
const value2 = useBreakpoint(1, [
    ['mobile', 2],
    ['ssr', 3]
]) // 3

Would something like that work out for you?

wintercounter avatar Sep 10 '20 16:09 wintercounter