Sometimes, we want to fix Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks.
In this article, we’ll look at how to fix Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks.
How to fix Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks?
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.
Conclusion
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.