Complete the code to import the React hook used for state.
import React, { [1] } from 'react';
The useState hook is used to add state to functional components.
Complete the code to create a custom hook that returns a count and a function to increase it.
function useCounter() {
const [count, setCount] = [1](0);
const increment = () => setCount(count + 1);
return { count, increment };
}The useState hook initializes the count state and provides a setter function.
Fix the error in the custom hook usage inside a component.
function Counter() {
const { count, increment } = [1]();
return <button onClick={increment}>{count}</button>;
}
function useCounter() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return { count, increment };
}The component must call the custom hook useCounter to get the count and increment function.
Fill both blanks to create a custom hook that tracks window width and updates on resize.
import { [1], [2] } from 'react'; function useWindowWidth() { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { const handleResize = () => setWidth(window.innerWidth); window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return width; }
useState manages the width state, and useEffect sets up and cleans the resize event listener.
Fill all three blanks to create a custom hook that fetches data and tracks loading state.
import { [1], [2] } from 'react'; function useFetch(url) { const [data, setData] = [3](null); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchData() { const response = await fetch(url); const json = await response.json(); setData(json); setLoading(false); } fetchData(); }, [url]); return { data, loading }; }
useEffect runs the fetch on mount or url change, and useState manages both data and loading states.