Order of Hooks

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 2Using 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 2Using the State Hook

At the moment, the order of Hooks is as follows:

  1. enableFirstName
  2. lastName

Next, we clicked on the checkbox to enable the firstName field. Doing so changed the order of Hooks, because now our Hook definitions look like this:

  1. enableFirstName
  2. firstName
  3. lastName

Since React solely relies on the order of Hooks to manage their state, the firstName field is now the second Hook, so it gets the state from the lastName field:

Problem of changing the order of Hooks from Chapter 2, Using the State Hook

If we use the real useState Hook from React in example 2 Can we define conditional Hooks? from Chapter 2Using the State Hook, we can see that React automatically detects when the order of Hooks has changed, and it will show a warning:

React printing a warning when detecting that the order of Hooks has changed

When running React in development mode, it will additionally crash with an Uncaught Invariant Violation error message when rendering more Hooks than in the previous render:

React crashing in development mode when the number of Hooks changed

As we can see, changing the order of Hooks or conditionally enabling Hooks is not possible, as React internally uses the order of Hooks to keep track of which data belongs to which Hook.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.111.9