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:
npx create-react-app react-useeffect-called-conditionally
Replicating the issue
Now update the App.js
with the following code:
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:
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.
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
Top comments (0)