Only call Hooks at the top level/beginning of function components or custom Hooks.
Do not call 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.
In Chapter 2, Using the State Hook, 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 firstName and lastName, and then we entered some text in the lastName field:
Revisiting our example from Chapter 2, Using the State Hook
At the moment, the order of Hooks is as follows:
- enableFirstName...