"Rendered fewer hooks than expected." ReactJS error

Published under React.

📺  Click here to skip to the video attached to this post  👇

In React, hooks must be called during render, and they must be called unconditionally and in the same order every render.

This means if you have a conditional if statement in your render logic, hooks cannot be within the conditional branch.

It also means that you cannot use hooks after your conditional statement, if your conditional statement returns early, ie:

In this case, if the loading prop is true, our component will return early resulting in the hook sometimes being called instead of always being called.

Okay, so what if I need to conditionally call a hook?

You can move the conditional logic inside of the hook:

The key is to make sure that all hooks you use are called every render, because React is tracking the hook calls (and their order!) behind the scenes.


Thanks for reading!

Did you find this post useful? Let me know on Twitter! If you found an issue with the content, submit a pull request!

Subscribe to my newsletter to know when I publish more content in the future.

❤️ Likes: 0
📣 Retweets: 0
💬 Replies: 0
🙊 Mentions: 0