React Hooks are fantastic and, used correctly, very powerful. But when it breaks, it all comes crashing down. None more so than with the relatively cryptic error:
React Hook use<Hook> is called conditionally. React Hooks must be called in the exact same order in every component render.
So, no mishmashing about with the order on different renders – why would you want to anyway?
The strictest rule of all with React Hooks – as the error message implies – Hooks in React must be called in exactly the same order every single time you render a component. No random number generators determining the order please!
If you break this sacred rule – you will get the dreaded React Hook use<blah> is called conditionally. The more common reason for this happening is if your using selection statements – if and the like – to determine which hooks are getting called based on the state or some other variable.
We’ll guide you through the solution below.
How to Fix It
Move your Hook Calls to the highest level. By placing them at the top level of your component, you ensure – just like any other sequence code – that they are actually all called in sequence – the same sequence – every time. Avoid using any selection statements or conditionals whatsoever – the means forgoing any if’s, loops, nested functions – basically anything that could disrupt the simple order that the hooks are applied in.
If you must use conditional rendering or statements – keep the hooks outside of these.
If you want conditional effects, the use the built in React capability of useEffect. Defining such effects inside this hook – also including any necessary dependencies – give you control of the effect being triggered without calling it conditionally.
When was the last time you reviewed your components? Maybe the out of sequence hooks are simply caused by a sprawling chasm of code. Make sure you review your component and ensure it’s there for one purpose and one purpose alone. Multiple purposes? Then split it out into the components it deserves to be!
Finally, if you want to venture into custom hooks, this will not only help you ensure the sequence is the same on every component render, but also ensure that you can use it across different components as well – even if they’ve not yet been created! Fixing this error and making your code more reusable is a win-win in our book!
Hope that helps, happy React hooking!