React docs state: don’t call Hooks inside loops, conditions, or nested functions.
Does calling a hook means just calling useState
e.g. const [state, useState] = useState(0)
?
What about calling setter in conditionals ?
Is this code breaking rules of hooks ?
const [oneHook, setOneHook] = useState(0)
const [anotherHook, setAnotherHook] = useState(false)
if (something) {
setOneHook(1)
setAnotherHook(true)
} else {
setOneHook(0);
setAnotherHook(false)
}
Thanks !
Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders.
The important thing is that the useState hook calls are made in the same order every time, because they're matched to the values they control by index (see overreacted.io/why-do-hooks-rely-on-call-order). There is no problem with calling the setter function inside a conditional.
Hooks should not be called within loops, conditions, or nested functions since conditionally executed Hooks can cause unexpected bugs. Avoiding such situations ensures that Hooks are called in the correct order each time the component renders.
Hooks are JavaScript functions, but they impose two additional rules: Only call Hooks at the top level. Don't call Hooks inside loops, conditions, or nested functions. Only call Hooks from React function components.
No, that code example does not break the rules of hooks. Every time the component renders there will be exactly the same number of calls to useState in exactly the same order, so that will be fine.
I do want to point out that setting state right away in the body of the component doesn't make much sense. When the component mounts it will start rendering with the initial values from state, but then before it can finish rendering the state has already changed and it has to start over. But presumably that's just an artifact of the example, and in your real code the if
would be inside a useEffect or some other practical code location.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With