T
TanStack10mo ago
ratty-blush

Get window width on server

Hi all! Please forgive me if this is a silly question. I am relatively new to SSR (via react at least) so I am struggling to do this properly. I have a component that needs to measure the window size to determine what border radius to use. Obviously there is no window on the server so I have to wait until the component renders on the client. But, I am getting a flash of incorrect style on the client before I measure the window and set the correct value. Is there a way to get window width (or at least browser type, etc) on the server. I started of with a useEffect solution and have now moved to a useState solution.
const [sm, setSm] = useState(false);

useEffect(() => {
if (typeof window !== 'undefined') {
setSm(window.innerWidth > 576);
}
}, []);

return <div style={{ borderRadius: sm ? 30 : 0 }}> </div>
const [sm, setSm] = useState(false);

useEffect(() => {
if (typeof window !== 'undefined') {
setSm(window.innerWidth > 576);
}
}, []);

return <div style={{ borderRadius: sm ? 30 : 0 }}> </div>
The above code has sm = false on the first render and then sets sm = true after. So there is a flash of wrongly styled content. What is the proper way to solve this? Do I need to return null until I have the data I need?
const [mounted, setMounted] = useState(false);
const [sm, setSm] = useState(false);

useEffect(() => {
if (typeof window !== 'undefined') {
setSm(window.innerWidth > 576);
}
setMounted(true);
}, []);

if (!mounted) {
return null;
}

return <div style={{ borderRadius: sm ? 30 : 0 }}> </div>
const [mounted, setMounted] = useState(false);
const [sm, setSm] = useState(false);

useEffect(() => {
if (typeof window !== 'undefined') {
setSm(window.innerWidth > 576);
}
setMounted(true);
}, []);

if (!mounted) {
return null;
}

return <div style={{ borderRadius: sm ? 30 : 0 }}> </div>
1 Reply
ratty-blush
ratty-blushOP10mo ago
Actually, that may affect SSR right? Rather than return null I should probably use display: mounted ? undefined : 'none'

Did you find this page helpful?