Skip to content
react

Fix - Rendered fewer hooks than expected in React

Apr 1, 2023Abhishek EH2 Min Read
Fix - Rendered fewer hooks than expected in React

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:

App.js
1import { useEffect, useState } from "react"
2
3function 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 }
11
12 // eslint-disable-next-line react-hooks/rules-of-hooks
13 useEffect(() => {
14 setHasError(true)
15 }, [])
16
17 return <div className="App">Loading</div>
18}
19
20export default App

If you run the code now, you will get the following error:

Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.

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:

App.js
1import { useEffect, useState } from "react"
2
3function App() {
4 const [hasError, setHasError] = useState(false)
5
6 useEffect(() => {
7 setHasError(true)
8 }, [])
9
10 if (hasError) {
11 const x = { foo: true }
12 if (x.foo) {
13 return <div>Error</div>
14 }
15 }
16
17 return <div className="App">Loading</div>
18}
19
20export default App

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

© 2024 CodingDeft.Com