Complete the code to create a state variable using React hooks.
const [count, [1]] = useState(0);
The useState hook returns a pair: the current state and a function to update it. The convention is to name the updater function starting with 'set'.
Complete the code to run a side effect only once when the component mounts.
useEffect(() => {
console.log('Component mounted');
}, [1]);Passing an empty array [] as the dependency list makes useEffect run only once after the first render (mount).
Fix the error in the cleanup function of useEffect to avoid memory leaks.
useEffect(() => {
const timer = setTimeout(() => {
console.log('Timeout');
}, 1000);
return () => [1];
}, []);To clear a timeout, use clearTimeout with the timer ID. This prevents the timeout from running if the component unmounts early.
Fill both blanks to update state and log the new value after the button click.
const handleClick = () => {
setCount([1]);
console.log('Count is now:', [2]);
};We update the count by adding 1, then log the current count value. Note that state updates are asynchronous, so logging the old count is expected here.
Fill all three blanks to fetch data on mount and store it in state.
useEffect(() => {
async function fetchData() {
const response = await fetch([1]);
const data = await response.[2]();
[3](data);
}
fetchData();
}, []);We fetch data from the URL, parse it as JSON, and update the state with setData. This runs once on mount due to the empty dependency array.