All quizzesEasy
Core Hooks — Series 3
Preview — 3 of 10 questions
After haveBirthday() runs, what is user?
javascript
const [user, setUser] = useState({ name: 'Ada', age: 36 });
function haveBirthday() {
setUser({ age: user.age + 1 });
}A{ name: 'Ada', age: 37 } — useState merges partial updates like this.setState
B{ name: 'Ada', age: 36 } — the update is ignored
C{ age: 37 } — useState's setter replaces the whole value; it does not shallow-merge like the class this.setState. You must spread the previous state yourself: setUser({ ...user, age: user.age + 1 })
DIt throws because name is missing
On the first mount, then one re-render, what is the log order?
javascript
function Logger() {
console.log('render');
useEffect(() => {
console.log('effect');
return () => console.log('cleanup');
});
return <div />;
}Arender, effect, then on re-render: render, cleanup, effect
Brender, effect, then on re-render: render, effect, cleanup
Ceffect, render, then effect, render
Drender, render, effect, effect
Why does React warn about this?
javascript
useEffect(async () => {
const data = await fetchData();
setData(data);
}, []);Aawait is not allowed inside useEffect
BfetchData must be memoized first
CsetData cannot be called in an effect
DAn async function always returns a Promise, but useEffect expects its callback to return either nothing or a cleanup function. Returning a Promise breaks the cleanup contract. The fix is to define an async function inside the effect and call it: useEffect(() => { (async () => { ... })(); }, [])
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.