Question du test React ⚛️

Écrire un composant React qui affiche le nombre 2

Intermédiaire

Que va afficher ce composant ?

const MyComponent = () => {
    const [index, setIndex] = useState(1);
    setIndex(2);
    return <div>{index}</div>;
}
Auteur: Vincent CotroStatut : PubliéeQuestion passée 3437 fois
Modifier
5
Évaluations de la communauté
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 !