Charbel
Charbel

Reputation: 37

React useState performing very badly

I am having trouble understanding the problem in this code:

    export default function CustomPopup({wi,he,children}) {

        //some code

        const [popupSize,setPopupSize] = useState([`${wi}px`,`${he}px`])
        
        const handlePopupSize = () =>{
            let c = [];
            (window.innerWidth < (wi/0.9)) ? c[0] = `90%` : c[0] = `${wi}px`;
            (window.innerHeight < (he/0.8)) ? c[1] = `80%` : c[1] = `${he}px`;
            if (c != popupSize) { setPopupSize(c) };
        }

        window.addEventListener("resize", handlePopupSize)

        return (
            
                <div className="popup--page--wrapper">
                    <div className="popup--box" style={{width: popupSize[0], height: popupSize[1]}}>  
                        { children }
                    </div>
                </div>
        )
    }

When I resize the page, the page lags massively and even make the browser bug. There seems to be something wrong with the code, but I can't find out. Thanks in advance!

Upvotes: 2

Views: 62

Answers (1)

Someone Special
Someone Special

Reputation: 13588

You need to add the event listener in a useEffect hook.

import React, { useState, useEffect } from 'react'
.....
.....
useEffect(() => {

    window.addEventListener("resize", handlePopupSize)
    return () => window.removeEventListener("resize", handlePopupSize)
},[])

Your current code creates a loop of addEventListeners, because a listener is created on every single render, and setting state is causing a new render on every resize.

Upvotes: 5

Related Questions