How to detect if screen size has changed to mobile in React?

const [isMobile, setIsMobile] = useState(false)
 
//choose the screen size 
const handleResize = () => {
  if (window.innerWidth < 720) {
      setIsMobile(true)
  } else {
      setIsMobile(false)
  }
}

// create an event listener
useEffect(() => {
  window.addEventListener("resize", handleResize)
})

// finally you can render components conditionally if isMobile is True or False 

What I did is adding an event listener after component mount:

componentDidMount() {
    window.addEventListener("resize", this.resize.bind(this));
    this.resize();
}

resize() {
    this.setState({hideNav: window.innerWidth <= 760});
}

componentWillUnmount() {
    window.removeEventListener("resize", this.resize.bind(this));
}

EDIT: To save state updates, I changed the "resize" a bit, just to be updated only when there is a change in the window width.

resize() {
    let currentHideNav = (window.innerWidth <= 760);
    if (currentHideNav !== this.state.hideNav) {
        this.setState({hideNav: currentHideNav});
    }
}

UPDATE: Time to use hooks! If you're component is functional, and you use hooks - then you can use the useMediaQuery hook, from react-responsive package.

import { useMediaQuery } from 'react-responsive';

...

const isMobile = useMediaQuery({ query: `(max-width: 760px)` });

After using this hook, "isMobile" will be update upon screen resize, and will re-render the component. Much nicer!


Using hooks in React(16.8.0+) refering to: https://stackoverflow.com/a/36862446/1075499

import { useState, useEffect } from 'react';

function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height
  };
}

export default function useWindowDimensions() {
  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return windowDimensions;
}

This is the same as @Ben Cohen answer but after attaching your function to eventListner, also remove it on componentWillUnmount

constructor() {
  super();
  this.state = { screenWidth: null };
  this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}

componentDidMount() {
    window.addEventListener("resize", this.updateWindowDimensions());
}

componentWillUnmount() {
    window.removeEventListener("resize", this.updateWindowDimensions)
}

updateWindowDimensions() {
   this.setState({ screenWidth: window.innerWidth });
}