DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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

Posted 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

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.