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!