Borislav Hadzhiev
Wed Apr 06 2022·2 min read
Photo by Taylor Brandon
The error "React hook 'useState' is called conditionally" occurs when we use
the useState
hook conditionally or after a condition that may return a value.
To solve the error, move all React hooks above any conditionals that may return
a value.
Here is an example of how the error occurs.
import React, {useState} from 'react'; export default function App() { const [count, setCount] = useState(0); if (count > 0) { return <h1>Count is greater than 0</h1>; } // ⛔️ React Hook "useState" is called conditionally. //React Hooks must be called in the exact same order // in every component render. Did you accidentally call // a React Hook after an early return? const [message, setMessage] = useState(''); return ( <div> <h2>Count: {count}</h2> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
The issue in the code snippet is - we use the second useState
hook after a
condition that may return a value.
To solve the error, we must only call React hooks at the top level.
import React, {useState} from 'react'; export default function App() { const [count, setCount] = useState(0); // 👇️ move hooks above condition that might return const [message, setMessage] = useState(''); // 👇️ any conditions that might return must be below all hooks if (count > 0) { return <h1>Count is greater than 0</h1>; } return ( <div> <h2>Count: {count}</h2> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
We moved the second useState
hook above the condition that might return a
value.
This means that we aren't allowed to use hooks inside loops, conditions or nested functions.
We should never call a hook conditionally.
import React, {useState} from 'react'; export default function App() { const [count, setCount] = useState(0); if (count === 0) { // ⛔️ React Hook "useState" is called conditionally. // React Hooks must be called in the exact same order in every component render. const [message, setMessage] = useState(''); } return ( <div> <h2>Count: {count}</h2> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
The code snippet above causes the error because we are calling the second
useState
hook conditionally.
This is not allowed because the number of hooks and the order of hook calls have to be the same on re-renders of our function components.
useState
call to the top level and not conditionally call the hook.Like the documentation states:
This helps React preserve the state of hooks between multiple useState
calls.