Skip to content
react

Fix - React Hook "useEffect" is called conditionally

Apr 1, 2023Abhishek EH2 Min Read
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:

1npx create-react-app react-useeffect-called-conditionally

Replicating the issue

Now update the App.js with the following code:

App.js
1import React, { useEffect, useState } from "react"
2
3const App = () => {
4 const [isLoading, setIsLoading] = useState(false)
5
6 if (isLoading) {
7 return <div>Loading..</div>
8 }
9
10 useEffect(() => {
11 // Load some data
12 setIsLoading(false)
13 }, [])
14
15 return <div>App</div>
16}
17
18export 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?

Understanding the issue

React is throwing the above error because we are calling useEffect 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.

App.js
1import React, { useEffect, useState } from "react"
2
3const App = () => {
4 const [isLoading, setIsLoading] = useState(false)
5
6 useEffect(() => {
7 // Load some data
8 setIsLoading(false)
9 }, [])
10
11 if (isLoading) {
12 return <div>Loading..</div>
13 }
14
15 return <div>App</div>
16}
17
18export default App

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com