Complete the code to define a custom hook that uses 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 call the custom hook inside a functional component.
function Counter() {
const [count, setCount] = [1]();
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}You call your custom hook useCounter inside the component to get the count and setter.
Fix the error in the custom hook by completing the missing return statement.
function useToggle(initialValue) {
const [value, setValue] = useState(initialValue);
function toggle() {
setValue(!value);
}
return [1];
}The hook should return both the current value and the toggle function as an array.
Fill both blanks to create a custom hook that fetches data and stores loading state.
import { useState, useEffect } from 'react'; function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { fetch(url) .then(response => response.json()) .then(json => { setData(json); setLoading([1]); }); }, [[2]]); return { data, loading }; }
After data is fetched, loading should be set to false. The effect depends on url to refetch when it changes.
Fill all three blanks to create a custom hook that debounces a value.
import { useState, useEffect } from 'react'; function useDebounce(value, delay) { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { const handler = setTimeout(() => { setDebouncedValue([1]); }, [2]); return () => { clearTimeout([3]); }; }, [value, delay]); return debouncedValue; }
The hook sets the debounced value to the current value after delay milliseconds. The timeout is cleared using the handler variable.