Are you working on a react application from the scratch and getting the following error while using hooks?
Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.
In this article, we will see why this error occurs, and how to fix it.
Replicating the issue
First, let's replicate the issue. Update your code with the following:
import { useEffect, useState } from "react"
function App() {
const [hasError, setHasError] = useState(false)
if (hasError) {
const x = { foo: true }
if (x.foo) {
return <div>Error</div>
}
}
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
setHasError(true)
}, [])
return <div className="App">Loading</div>
}
export default App
If you run the code now, you will get the following error:
Understanding the issue
The above error occurs because, we have a return statement inside the conditions and after the return, we are having useEffect hook. As the rule of hooks, we should run all the hooks irrespective of conditions. So we need to maintain all the hook calls before any return statement.
Fixing the issue
Moving the useEffect hook above the if conditions should fix the issue:
import { useEffect, useState } from "react"
function App() {
const [hasError, setHasError] = useState(false)
useEffect(() => {
setHasError(true)
}, [])
if (hasError) {
const x = { foo: true }
if (x.foo) {
return <div>Error</div>
}
}
return <div className="App">Loading</div>
}
export default App
Top comments (3)
Just encountered the same err, please keep in mind sometimes it is not as easy as this case -- violated rules 😂
But rather a bit complex. TBF I did not resolve the issue myself. So just commenting :kidding:
thnx for the simple answer
was helpful, thanks