The Rules of hooks states that you must only call a hook at the top level, meaning you can’t call it inside a conditional branch. However, it is perfectly fine to call the setState
function it inside a branch because it is not a hook itself, just a function to trigger a state update.
So it is fine to do A but not B
// A: Valid
function example(){
const [state, setState] = useState();
useEffect(() => {
if(true){
somePromiseTwo().then((result) => setState(result));
}else{
somePromiseOne().then((result) => setState(result));
}
}, […]);
}
// B: not valid
function example(){
if(true){
const [state, setState] = useState();
}else{
// …
}
}
However, note that I put your async logic inside a useEffect hook. Why? Because your function can be called an arbitrary number of times by React, and you don’t want the async logic to trigger every time it is called. The idiomatic way to control when and how often it is called in a custom hook/component in React is by using useEffect
. You can read more about it here