# Fix - React Hook "useEffect" is called conditionally

If you have started using react hooks recently, you might have come across the following error:

`React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?`

In this article, we will try to replicate the error, see why the error occurs and will fix the error.

## Project Setup

Create a react project using the following command:

```bash
npx create-react-app react-useeffect-called-conditionally
```

## Replicating the issue

Now update the `App.js` with the following code:

```jsx
import React, { useEffect, useState } from "react"

const App = () => {
  const [isLoading, setIsLoading] = useState(false)

  if (isLoading) {
    return <div>Loading..</div>
  }

  useEffect(() => {
    // Load some data
    setIsLoading(false)
  }, [])

  return <div>App</div>
}

export default App
```

If you try to run the app, you will see the following error in the browser:

![React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?](https://cdn.hashnode.com/res/hashnode/image/upload/v1661062521969/A-cX2_b3D.png) 

## Understanding the issue

React is throwing the above error because we are calling [useEffect](https://www.codingdeft.com/posts/react-useeffect-hook/) after the return statement (inside `isLoading` check). It is mandatory that all the hooks are defined before any return statement.

## The fix

The fix is simple. Just move the useEffect block before the if condition and the code should work fine.

```jsx
import React, { useEffect, useState } from "react"

const App = () => {
  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    // Load some data
    setIsLoading(false)
  }, [])

  if (isLoading) {
    return <div>Loading..</div>
  }

  return <div>App</div>
}

export default App
```
