React Data Fetching and Effects Quiz
Four drills on fetching data with useEffect, avoiding stale closures, and cleaning up in-flight requests when the component unmounts or the input changes.
Question Bank
Medium
JavaScript
4 questions
quiz
react
hooks
js-fetch-api
423 views
3
Write a <UserCard userId={id} /> that fetches /api/users/:id and shows the name. Handle loading, error, and the id-changes case.
This counter logs the same number forever after the first click. Explain the stale-closure bug, then fix it.
import { useEffect, useState } from 'react';
function Logger() {
const [n, setN] = useState(0);
useEffect(() => {
const id = setInterval(() => console.log(n), 1000);
return () => clearInterval(id);
}, []);
return <button onClick={() => setN((x) => x + 1)}>{n}</button>;
}When should data fetching live in a custom hook versus in the component? Name two concrete benefits of extracting it.
Why is it usually a bug to call setState from a fetch .then() without checking whether the component is still mounted? Show the safe pattern using AbortController.
