The approach behind re-rendering a React component on window resize can be broken down into three steps.
Let's take a look at an example to sort the confusion.
export const App = () => {
const [windowWidth, setWindowWidth] = useState(window.innerWidth)
const [windowHeight, setWindowHeight] = useState(window.innerHeight)
const setWindowDimensions = () => {
setWindowWidth(window.innerWidth)
setWindowHeight(window.innerHeight)
}
useEffect(() => {
window.addEventListener('resize', setWindowDimensions);
return () => {
window.removeEventListener('resize', setWindowDimensions)
}
}, [])
return(
<div>Width: {windowWidth} Height: {windowHeight}</div>
)
}
export default App
As described in the above steps, first I created two state variables to hold the window width and height.
const [windowWidth, setWindowWidth] = useState(window.innerWidth)
const [windowHeight, setWindowHeight] = useState(window.innerHeight)
Then I created a function to update the window width and height state variables.
const setWindowDimensions = () => {
setWindowWidth(window.innerWidth)
setWindowHeight(window.innerHeight)
}
As the third step, I added resize event listeners to call the
useEffect(() => {
window.addEventListener('resize', setWindowDimensions);
return () => {
window.removeEventListener('resize', setWindowDimensions)
}
}, [])
This method is ok for single use. To make this functionality more reusable, we can move this logic into a custom hook. That makes it easy to reuse this resize detection functionality as a utility component.
export const useWindowSize = (): number[] => {
const [windowSize, setWindowSize] = useState([0,0])
const updateWindowSize = () => {
setWindowSize([window.innerWidth, window.innerHeight])
}
useLayoutEffect(() => {
window.addEventListener('resize', updateWindowSize);
updateWindowSize();
return () => window.removeEventListener('resize', updateWindowSize);
},[])
return [windowSize[0], windowSize[1]]
}
The usage is simple as importing and using the
import { useWindowSize } from "./components/useWindowSize"
export const App = () => {
const [width, height] = useWindowSize()
return(
<div>
<div><h3>React js window dimensions</h3></div>
<div>Width: {width}</div><div>Height: {height}</div>
</div>
)
}
export default App