Complete the code to create a custom hook that uses React's useState.
import { useState } from 'react'; function useCounter() { const [count, setCount] = [1](0); return [count, setCount]; }
The useState hook is used to add state to a custom hook.
Complete the code to ensure the custom hook returns a memoized callback.
import { useCallback } from 'react'; function useLogger() { const log = [1](() => { console.log('Logging'); }, []); return log; }
useCallback memoizes a function so it does not get recreated on every render.
Fix the error in the custom hook by completing the missing import.
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
export default useWindowWidth;
// Missing import: import [1] from 'react';The hook uses useState but it was not imported. Importing it fixes the error.
Fill both blanks to create a custom hook that fetches data and stores loading state.
import { useState, [1] } from 'react'; function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = [2](true); // fetching logic here }
useEffect is used to run side effects like fetching data, and useState manages loading state.
Fill all three blanks to create a custom hook that toggles a boolean state.
import { useState } from 'react'; function useToggle(initialValue = false) { const [value, setValue] = useState([1]); const toggle = () => setValue([2] => ![3]); return [value, toggle]; }
Initialize state with false. The toggle function uses the previous state prev to invert the value.