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 3862 times
Edit
8
Community Evaluations
Incorrect answer
Madaa20/01/2025
When we put debugger into this component we can see that this component displays 1 and after first component render useEffect effect has called, effect sets new value component render one more time and only now we see 2
Correct answers are:
It will display: 1
and
It will display: 2
Ambiguous
Auteur anonyme15/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?
Dragon parfait
26/08/2024
I think it's not ambiguous to most people. It's classified as very easy because of this.
Rémi
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.
25
Write the missing code to render the children of the UserProfile component.28
Write the non-JSX equivalent of the following code:14
Call a function on the first render of a React component14
Save the state used to display the selected page in a React component.15
Write a React component as a function10
Write a React component that updates the document title with each click and resets to 'React App' when the component unmounts.9
Use useCallback to optimize rendering in React