Question from the React ⚛️ test

UseState and useEffect in React

Easy

What will this component display?

const MyComponent=()=>{
    const[index, setIndex]= useState(1);

    useEffect(()=>{
        setIndex(2);
    },[]);

    return<div>{index}</div>;
};
Author: Vincent CotroStatus: PublishedQuestion passed 3392 times
Edit
8
Community Evaluations
developer avatar
Ambiguous
Auteur anonyme
15/08/2024
The component will display 1 initially, and then call useEffect which will update the state and then 2 is displayed, so I think the question is ambiguous, it should ask what will it show last?
developer avatar
Auteur anonyme
26/08/2024
I think it's not ambiguous to most people. It's classified as very easy because of this.
developer avatar
Auteur anonyme
17/09/2024
Effectivement, le cycle de vie du composant est modifié par le useEffect; il affichera "1" au premier rendu, mais il sera executé par la suite (une seule fois vu le tableau de dépendances) et mettra à jour le state, index vaudra alors "2", et donc le composant sera rendu à nouveau.