Para usar

Código simples com addEventListener para evento resize
mail@pastecode.io avatar
unknown
javascript
a month ago
860 B
1
Indexable
Never
const MOBILE_WIDTH = 600

const WelcomeNewCentury = () => {
  const [isMobile, setIsMobile] = useState(window.innerWidth <= MOBILE_WIDTH)
  const prevWidth = useRef(window.innerWidth)

  const handleResize = useCallback(() => {
    console.log('Called on resize!')
    
    const currWidth = window.innerWidth
    if (currWidth <= MOBILE_WIDTH && prevWidth.current > MOBILE_WIDTH){
      setIsMobile(true)
    } else if (currWidth > MOBILE_WIDTH && prevWidth.current <= MOBILE_WIDTH) {
      setIsMobile(false)
    }
    prevWidth.current = currWidth
  }, [])

  useEffect(() => {
    window.addEventListener("resize", handleResize)
    return () => window.removeEventListener("resize", handleResize)
  }, [])

  return (
    <>
      { isMobile ? <section>Is mobile</section> : <section>Is Full size</section> }
    </>
  )
}

export default WelcomeNewCentury
Leave a Comment