Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does calling setter of useState hook inside if statement imply BREAKING RULES OF HOOKS?

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 !

like image 484
max23701 Avatar asked Nov 01 '19 04:11

max23701


People also ask

Can Hooks be called inside if statement?

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.

Can I use useState inside if statement?

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.

Why should we never call Hooks inside loops conditions or nested functions?

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.

Can you call a hook within a hook React?

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.


1 Answers

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.

like image 181
Nicholas Tower Avatar answered Oct 30 '22 19:10

Nicholas Tower