Complete the code to create a custom hook that uses state.
import { useState } from 'react'; function useCounter() { const [count, setCount] = [1](0); return [count, setCount]; }
The useState hook is used to add state inside a custom hook.
Complete the code to use the custom hook inside a component.
function Counter() {
const [count, setCount] = [1]();
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}The custom hook useCounter is called like a regular function to get state and updater.
Fix the error in the custom hook to avoid violating React rules.
function useCounter() {
if (true) {
const [count, setCount] = [1](0);
}
return [count, setCount];
}Hooks must be called unconditionally at the top level of the function, not inside if statements.
Fill both blanks to create a custom hook that fetches data and stores it in state.
import { useState, useEffect } from 'react'; function useData(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then(response => response.[1]()) .then(json => setData(json)); }, [[2]]); return data; }
The response.json() method parses the response body as JSON.
The effect depends on url so it runs again if the URL changes.
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]; }
The state starts with initialValue.
The toggle function uses the previous value to set the opposite boolean.