Categories
React Answers

How to fix Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks?

Spread the love

To fix Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks, we should put hook calls at the top level of a component.

For instance, we write

const { useState } = React;

function App() {
  const [name, setName] = useState("Mary");
  const [age, setAge] = useState(16);
  const [license, setLicense] = useState("A123456");

  return (
    <div>
      Name:{" "}
      <input
        value={name}
        onChange={(e) => {
          setName(e.target.value);
        }}
      />
      <br />
      Age:{" "}
      <input
        value={age}
        type="number"
        onChange={(e) => {
          setAge(+e.target.value);
        }}
      />
      {age >= 16 && (
        <span>
          <br />
          Driver License:
          <input
            value={license}
            onChange={(e) => {
              setLicense(e.target.value);
            }}
          />
        </span>
      )}
    </div>
  );
}

to call useState at the top of the App component only.

Then React can call all the hooks in order.

We should not nest any hooks in our component.

Otherwise, we’ll get this error.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *