Skip to content
react

Fix - React Hook "useState" is called conditionally

Dec 17, 2022Abhishek EH2 Min Read
Fix - React Hook "useState" is called conditionally

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:

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

If you update App.js to the above code, you will get 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?

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"
2
3const App = () => {
4 const [isLoading, setIsLoading] = useState(false)
5 const [data, setData] = useState({})
6
7 if (isLoading) {
8 return <div>Loading..</div>
9 }
10
11 return <div>Home</div>
12}
13
14export default App

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

© 2024 CodingDeft.Com