[Solved] Uncaught Invariant Violation: Rendered more hooks than during the previous render

When you are working with React Hooks, you may see the error: Uncaught Invariant Violation: Rendered more hooks than during the previous render. In this article, we will show you how to fix this article.

If we conditionally call a hook or return before all of the hooks have finished, we get the error “Rendered more hooks than during the last render”. Move all hooks to the top level of the function component and avoid using hooks within conditions to fix the problem.

Error

Uncaught Invariant Violation: Rendered more hooks than during the previous render.
Error - Uncaught Invariant Violation: Rendered more hooks than during the previous render - Clue Mediator
Error – Uncaught Invariant Violation: Rendered more hooks than during the previous render – Clue Mediator

Let’s take an example of how the error occurs and how to fix it.

Example 1

Solution:

Because React hooks can only be invoked at the top level, we must relocate the condition within the hook to fix the issue.

Example 2

Solution:

To fix the issue, we must shift all hooks to the component’s top level, above any circumstances that can result in a return value.

Conclusion

  • Call hooks only at the top level.
  • Calling hooks inside of loops, conditions, or nested functions is not recommended.
  • Use hooks first, before any early returns, in the top level of your React method.
  • Only call hooks from React function components or from custom hooks.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! πŸ™‚

If you found value in this article,
you can support us by buying me a coffee! β˜•

You may also like...

Leave a Reply

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