Table of Contents
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:
1import { useEffect, useState } from "react"23function App() {4 const [hasError, setHasError] = useState(false)5 if (hasError) {6 const x = { foo: true }7 if (x.foo) {8 return <div>Error</div>9 }10 }1112 // eslint-disable-next-line react-hooks/rules-of-hooks13 useEffect(() => {14 setHasError(true)15 }, [])1617 return <div className="App">Loading</div>18}1920export 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:
1import { useEffect, useState } from "react"23function App() {4 const [hasError, setHasError] = useState(false)56 useEffect(() => {7 setHasError(true)8 }, [])910 if (hasError) {11 const x = { foo: true }12 if (x.foo) {13 return <div>Error</div>14 }15 }1617 return <div className="App">Loading</div>18}1920export default App
Do follow me on twitter where I post developer insights more often!
Leave a Comment