I have the following hook that I use to build responsive components throughout my App.
I looking into implementing Server Side Rendering.
useWindowWidth.js
import {useEffect, useRef, useState} from 'react';
function useWindowWidth() {
const hasResized = useRef(false);
const [windowSize,setWindowSize] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
if (hasResized.current === true) {
return;
}
hasResized.current = true;
throtled_forceUpdate();
}
function throtled_forceUpdate() {
setTimeout(()=>{
// console.log('I will be updated!');
// console.log(window.innerWidth);
setWindowSize(window.innerWidth);
hasResized.current = false;
},250);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowSize;
}
export default useWindowWidth;
App.js
import React from 'react';
import useWindowWidth from './hooks/useWindowWidth';
function App(props) {
const windowWidth = useWindowWidth();
return(
windowWidth > 1200 ?
<DesktopLayout/>
: <MobileLayout/>
);
}
ReactDOMServer
ReactDOMServer.renderToString(App);
What is the ReactDOMServer behavior when it encounters something like this? What is the workaround for this kind of situation?