Question from the React ⚛️ test

Write a React component that displays the number 2

Medium

What will this component display?

const MyComponent=()=>{
    const[index, setIndex]= useState(1);
    setIndex(2);
    return<div>{index}</div>;
}
Author: Vincent CotroStatus: PublishedQuestion passed 3316 times
Edit
4
Community Evaluations
developer avatar
Capucine
10/11/2023
Don't understand why it will create an infinite loop
developer avatar
Auteur anonyme
13/11/2023
Because updating your state will create a new render. You should only update your state conditionnaly (for exemple using a "onClick" or a condition) The loop will look like this : - Rendering - Updating state (with setIndex(2)) - Rendering - Updating state (with setIndex(2)) etc...
developer avatar
Capucine
13/11/2023
Thank you for the explanation !