React Hook useXXX is called conditionally. React Hooks must be called in the exact same order in every component render

It is a common ESLint warning in React. ESLint is a popular tool that helps developers catch and fix common programming mistakes.

When this error occurs, your code editor might display the following error message 👇

React hook "usexxxx" is called conditionally error pic 1.

Why this error occurs ?

This error occurs when you use a React Hook, such as “useState” or “useEffect“, in a wrong way. Hooks cannot be called conditionally, inside loops, or nested in any other functions or blocks.

If you use Hooks conditionally in React, it can cause issues like changing the order of the Hooks or skipping some Hooks altogether. This can lead to unexpected behavior, incorrect state, and can break React’s assumptions about the component structure.

Here’s an example of how you might get the error:

// Incorrect code
function MyComponent() {
  if (someCondition) {
// ⛔️ React Hook useState is called conditionally.
    const [count, setCount] = useState(0);
    // ...
  }
  // ...
}

How to fix this error ?

To fix the error you need use React Hooks correctly. It’s important to note that Hooks should always be called at the top level of your component function and not inside any other functions or nested blocks. This ensures that Hooks are called on every render and React can properly manage their state.

Here’s an example of how you might refactor code that caused the error:

// Corrected code
function MyComponent() {
  const [count, setCount] = useState(0);

  if (someCondition) {
    // ...
  }
  // ...
}

Hope this article helped you fix and understand the error 🙏

Leave a Comment