Table of Contents
Have you started using React hooks recently and got the following error?
React Hook "useState" 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 see why this error occurs, and how to fix it.
Replicating the issue
First, let's replicate the issue:
1import React, { useState } from "react"23const App = () => {4 const [isLoading, setIsLoading] = useState(false)56 if (isLoading) {7 return <div>Loading..</div>8 }9 const [data, setData] = useState({})1011 return <div>Home</div>12}1314export default App
If you update App.js
to the above code, you will get the following error :
Understanding the issue
Before fixing the issue, let's understand the issue. As the error message indicates, you should not call useState after the return statement or inside an if condition. React hook calls should always happen before any return statement and preferably at the top of the component.
Fixing the issue
To fix the error, you just need to move the useState call before the if condition:
1import React, { useState } from "react"23const App = () => {4 const [isLoading, setIsLoading] = useState(false)5 const [data, setData] = useState({})67 if (isLoading) {8 return <div>Loading..</div>9 }1011 return <div>Home</div>12}1314export default App
Do follow me on twitter where I post developer insights more often!
Leave a Comment