Order of Hooks
Only use Hooks at the top level (not nested), ideally at the beginning of function components or custom Hooks, like so:
function ExampleComponent() {
const [name, setName] = useState('')
// …
}
function useCustomHook() {
const [name, setName] = useState('')
return { name, setName }
}
Do not use Hooks inside conditions, loops, or nested functions—doing so changes the order of Hooks, which causes bugs. We have already learned that changing the order of Hooks causes the state to get mixed up between multiple Hooks.
To recap, in Chapter 2, Using the State Hook, in Example 2, we learned that we cannot do the following:
const [enableFirstName, setEnableFirstName] = useState(false)
const [name, setName] = enableFirstName
? useState('')
: ['', () => {}]
const [lastName, setLastName] = useState('')
We rendered a checkbox and two input fields for the first name and last name,...