JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Rendered fewer hooks than expected error in React

Author:JIYIK Last Updated:2025/03/15 Views:

When we use a hook after a condition that might return a value, we get the error “Rendered fewer hooks than expected. This may be caused by an accidental early return statement.” To fix the error, you need to move all React hooks above any condition that might return a value.

First, let's look at an example that produces this error

import {useEffect, useState} from 'react';

export default function App() {
  const [counter, setCounter] = useState(0);

  // 可能在下面的钩子运行之前返回一个值
  if (counter > 0) {
    return <h1>Hello world</h1>;
  }

  // Rendered fewer hooks than expected.
  // This may be caused by an accidental early return statement
  const [message, setMessage] = useState('');

  return (
    <div>
      <button onClick={() => setCounter(counter + 1)}>Increment count</button>
    </div>
  );
}

The problem in your code snippet is - we use a second useState hook after the conditional that might return a value.

To fix this error, we can only call React hooks at the top level.

import {useEffect, useState} from 'react';

export default function App() {
  const [counter, setCounter] = useState(0);

  // 将钩子移到可能返回的条件之上
  const [message, setMessage] = useState('');

  // 任何可能返回的条件都必须低于所有钩子
  if (counter > 0) {
    return <h1>Hello world</h1>;
  }

  return (
    <div>
      <button onClick={() => setCounter(counter + 1)}>Increment count</button>
    </div>
  );
}

We move the second useState hook above the conditional that might return a value.

This fixes the error since we have to make sure that the React hooks are called in the same order every time we render the component.

This means that we are not allowed to use hooks in loops, conditionals or nested functions.

We have to make sure that all React hooks in our component are called in the same order on every render.

We should never call hooks conditionally.

import {useEffect, useState} from 'react';

export default function App() {
  const [counter, setCounter] = useState(0);

  if (counter > 0) {
    // Error - useEffect is called conditionally
    useEffect(() => {
      console.log('hello world');
    }, []);
  }

  return (
    <div>
      <button onClick={() => setCounter(counter + 1)}>Increment count</button>
    </div>
  );
}

The code snippet in the example will result in an error because the useEffect hook is called conditionally.

To fix this, we can move the if statement into the useEffect hook.

import {useEffect, useState} from 'react';

export default function App() {
  const [counter, setCounter] = useState(0);

  useEffect(() => {
    if (counter > 0) {
      console.log('hello world');
    }
  }, [counter]);

  return (
    <div>
      <button onClick={() => setCounter(counter + 1)}>Increment count</button>
    </div>
  );
}

Moving the if statement inside the hook helps because the hook is now top-level and has predictable behavior, allowing React to correctly preserve state between useState and useEffect calls.

As the documentation states:

  • Only call hooks at the top level
  • Do not call hooks in loops, conditionals, or nested functions
  • Always use hooks at the top level of a React function, before any early returns
  • Hooks are only called from React function components or custom hooks.

This helps React preserve the state of the hook between multiple useState and useEffect calls.

The error "Rendered fewer hooks than expected. This may be caused by an accidental early return statement" means that we rendered more hooks on the first render of the component than on re-renders. This is caused by conditionally returning before using the hook.

To fix the error, you need to make sure you move your hook to the top level of your component and put any conditionals that might return prematurely at the bottom.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to avoid cross-origin (CORS) issues in React/Next.js

Publish Date:2025/03/17 Views:170 Category:NETWORK

In this article, we will introduce how to avoid cross-origin (CORS) issues in React/Next.js. Cross-origin resource sharing (CORS) is a protocol that defines how web requests should be handled when crossing different URLs.

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:188 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:187 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:102 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:60 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:191 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial