Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does adding extra arrow function parentheses resolve an infinite loop problem?

I’m working on my project using react but I encountered a problem with using setState hook.

Here is my code:

//state and handle function

const [activeStep, setActiveStep] = React.useState(0);
const handleStep = (index)  => {
        setActiveStep(index);
}

//return component (I'm using mui)

return (
            <Stepper nonLinear activeStep={activeStep}>
                {steps.map((label, index) => (
                    <Step key={label} completed={false}>
                        <StepButton color="inherit" onClick={handleStep(index)}>
                            {label}
                        </StepButton>
                    </Step>
                ))}
            </Stepper>

    );

With this code page enters infinite loop and the page doesn’t show up. But if I add an extra parentheses to handlestep function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//added extra parantheses
const handleStep = (index) => () => {
        setActiveStep(index);
    }

It doesn’t enter infinite loop and everything seems working.
Does adding parentheses to arrow functions changes functionality or is it a MUI component bug?

>Solution :

You are calling function instead of passing.

Change this

<StepButton color="inherit" onClick={handleStep(index)}>

Into this

<StepButton color="inherit" onClick={() => handleStep(index)}>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading