0

I have started to learn React and run into a Problem. I try to establish a Event Handler that listens for window resizes and changes a State acocordingly, letting me enable or disable certain components on the page for different screen sizes.

Unfortunatly I run into the problem of a resetting state variable. And I dont really know why it does. Hopefully you guys can halp me here :)

This is my Code:

import React, { useRef, useState, useEffect } from "react"

export default function Home() {

  const size = useRef(null)
  const [a, rerender] = useState(0)

  const mobileFrontpageSwitch = () => {
    if (window.innerWidth > 1350 && size.current !== "XL") {
      size.current = "XL"
      rerender(a + 1)
      console.log(a + " : " + size.current)
    } else if (
      window.innerWidth <= 1350 &&
      window.innerWidth > 1024 &&
      size.current !== "L"
    ) {
      size.current = "L"
      rerender(a + 1)
      console.log(a + " : " + size.current)
    } else if (
      window.innerWidth <= 1024 &&
      window.innerWidth > 550 &&
      size.current !== "M"
    ) {
      size.current = "M"
      rerender(a + 1)
      console.log(a + " : " + size.current)
    } else if (window.innerWidth <= 550 && size.current !== "S") {
      size.current = "S"
      rerender(a + 1)
      console.log(a + " : " + size.current)
    }
  }
  useEffect(() => {
    mobileFrontpageSwitch()

    window.addEventListener("resize", mobileFrontpageSwitch)
    console.log("Added Resize Handler")

    return () => {
      // clean up the event handler when the component unmounts
      window.removeEventListener("resize", mobileFrontpageSwitch)
      console.log("Removed Resize Handler")
    }
  }, [])
  return(
    [...]
  )
}

BreakPoints are placeholders. Output when Resizing is something like this:

0 : XL
0 : L
0 : M
0 : L
0 : M
0 : S

It also does not rerender when Breakpoints are hit.

Does anyone know why this happens?

Thanks a lot!

Ferran Buireu
  • 24,410
  • 6
  • 32
  • 55
nico95
  • 1
  • 1
  • this is just because setting state is asynchronous - in your case, calling `rerender` doesn't update the value `a` at once, but simply schedules another render in which `a` will have the new value. It's not clear you have any actual problem here - `a` doesn't seem to actually affect anything outside your `console.log`s, and that resize function only fires once when the component first renders anyway. And it's the `size` ref which is going to contain the information you need about window size, not `a`? – Robin Zigmond Jun 20 '21 at 09:50

0 Answers0