Table of Contents
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:
1import React, { useEffect, useState } from "react"23const App = () => {4 const [isLoading, setIsLoading] = useState(false)56 if (isLoading) {7 return <div>Loading..</div>8 }910 useEffect(() => {11 // Load some data12 setIsLoading(false)13 }, [])1415 return <div>App</div>16}1718export 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.
1import React, { useEffect, useState } from "react"23const App = () => {4 const [isLoading, setIsLoading] = useState(false)56 useEffect(() => {7 // Load some data8 setIsLoading(false)9 }, [])1011 if (isLoading) {12 return <div>Loading..</div>13 }1415 return <div>App</div>16}1718export default App
Do follow me on twitter where I post developer insights more often!
Leave a Comment