How to update immediately with useEffect screen window width value, not only after browser is refreshed

36 views Asked by At

I have relatively simple code.

I want to check with useEffect the size of the window (width) and at lower resolution change the state to false/true.

const Header = ({ mobileSidebarToggle, toggleMobileSidebar }) => {
  const { sidebarToggle, toggleSidebar } = useContext(SidebarContext)
  const [isMobile, setIsMobile] = useState(false)

  const checkMobile = () => {
    if (window.innerWidth < 1280) {
      setIsMobile(true)
    } else {
      setIsMobile(false)
    }
  }
  useEffect(() => {
    window.addEventListener('resize', checkMobile)
  }, [window.innerWidth])

The code works, but only after i refresh browser. This is causing some problems, like navigation disappearing, which is turning off/on based on state "isMobile".

I simply want the code to update the flag at once the window is resized by the user (for example when he shifts the window browser),not only after i refresh the aplication with the browser and re-render everything.

I was thinking that adding [window.innerWidth]) dependancy will fix the issue, but it did not changed anything.

What I overlooked ?

0

There are 0 answers