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:
//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)}>