DEV Community

Cover image for Fix - Rendered fewer hooks than expected in React
collegewap
collegewap

Posted on • Updated on • Originally published at codingdeft.com

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:

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
Enter fullscreen mode Exit fullscreen mode

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:

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
Enter fullscreen mode Exit fullscreen mode

Oldest comments (3)

Collapse
 
akramadil profile image
Akram Adil

was helpful, thanks

Collapse
 
jasonworkgit profile image
jason

thnx for the simple answer

Collapse
 
nodejsdeveloperskh profile image
node.js.developers.kh

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: