Home > Software design >  While Loop freezes page in React
While Loop freezes page in React

Time:04-22

Not sure if I'm missing something here, but a very simple while loop is freezing the page.

Checked:

Console logged inside useEffect to check if component re-rendering unusually, but that's not the case.

function IterationComponent() {

    const [c1, incrementC1] = useState(() => 0);
    const [c2, incrementC2] = useState(() => 0);

    useEffect(() => {
        console.log(1)
    }); 

    function incrementC1Fn () {
        incrementC1(prevValue => prevValue   1)
    }

    function incrementC2Fn () {
        incrementC2(prevValue => prevValue   1)
    }

    const isEven = () => {
        let i = 0;
        while(i < 2); i  
        return c1 % 2 === 0;
    }

    return (
        <>
            <button onClick={incrementC1Fn}>C1 - {c1}</button>
            <button onClick={incrementC2Fn}>C2 - {c2}</button>
            <span>{isEven() ? 'Even' : 'Odd'}</span>
        </>
    
    )
}

Whenever I'm adding the while loop inside isEven function, then the page freezes as I'm not able to click any button

NOTE: Please don't ask me why I am doing something like this or what's the purpose of this or I can do this in some other way to increase the performance. This is just for my understanding as I want to deliberately make the isEven function works slowly. It's just for educational purpose. But I think this simple while loop shouldn't freeze the page unless I'm doing something wrong here.

CodePudding user response:

The issue is on this line while(i < 2); i . You should change it to while(i < 2) i ;.

while(i < 2); will always evaluate to true which will execute infinitely and will in turn freeze the page.

  • Related