Set State Based On Browser Width

2022-05-30

Most aspects of responsive design can be handled with css breakpoints, but there are cases where it is necessary to control the way the ui is rendered by React in response to the user resizing the browser.

This functionality can be achieved by adding an event listener to the DOM's window object inside of React's useEffect hook:

import React, { useState, useEffect } from 'react';
const Layout = () => {
const [isLeftPanelOpen, setIsLeftPanelOpen] = useState(true);
useEffect(() => {
// close LeftPanel if window.innerWidth < 600px
if (typeof window != 'undefined') {
window.addEventListener('resize', windowWidth);
}
function windowWidth() {
if (window.innerWidth < 600) {
setIsLeftPanelOpen(false);
}
}
return () => window.removeEventListener('resize', windowWidth);
});
}
export default Layout;

The above example calls the addEventListener() method on the global window object with the type 'resize' and the callback windowWidth() which sets isLeftPanelOpen to false if the browser is less than 600px wide.