Complete the code to run the effect only once when the component mounts.
useEffect(() => {
console.log('Component mounted');
}, [1]);Using an empty array [] as the dependency list makes the effect run only once when the component mounts.
Complete the code to run the effect whenever the 'count' state changes.
useEffect(() => {
console.log(`Count changed: ${count}`);
}, [1]);Including count in the dependency array makes the effect run whenever count changes.
Fix the error in the cleanup function to avoid memory leaks.
useEffect(() => {
const timer = setTimeout(() => {
console.log('Timer done');
}, 1000);
return () => [1];
}, []);The cleanup function should call clearTimeout(timer) to cancel the timer and prevent memory leaks.
Fill both blanks to update the document title with the current count and clean up properly.
useEffect(() => {
document.title = `Count: ${count}`;
return () => [1];
}, [2]);The cleanup logs a message, and the effect runs whenever count changes, so [count] is the dependency array.
Fill all three blanks to fetch data on mount, update state, and clean up properly.
useEffect(() => {
const controller = new AbortController();
fetch('https://api.example.com/data', { signal: [1] })
.then(response => response.json())
.then(data => [2](data))
.catch(error => {
if (error.name !== 'AbortError') {
console.error(error);
}
});
return () => [3];
}, []);The fetch uses controller.signal to allow aborting. The data is set with setData. The cleanup aborts the fetch with controller.abort().