Night
Night

Reputation: 41

ReactJS hooks: update state inside condition

everyone!

Can some one tell me if updating state inside if / else statement is acceptable by React rules. In particular updating state based on the result of a promise inside of the condition.

For example:

import {useState} from "react";
import {somePromiseOne, somePromiseTwo} from "./example";

function example(){

  const [state, setState] = useState();

  if(true){
    somePromiseTwo().then((result) => setState(result));
  }else{
    somePromiseOne().then((result) => setState(result));
  }

}

Upvotes: 1

Views: 1425

Answers (4)

felinebaron
felinebaron

Reputation: 11

Yes, it is acceptable. For example:

Promise.resolve().then(() => {
  setState("newState");
});

would work just fine.

Upvotes: 0

Son Nguyen
Son Nguyen

Reputation: 1777

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

Upvotes: 1

Shadi Amr
Shadi Amr

Reputation: 510

Yes why not :

const promiseFunc = isCondidtionValid ? somePromiseTwo : somePromiseOne;
promiseFunc().then(result => setState(result));

Upvotes: 0

CptSosen
CptSosen

Reputation: 158

It is acceptable to use state inside condition. If you want to know what are rules of React hooks you can read about it here: https://reactjs.org/docs/hooks-rules.html

Upvotes: 0

Related Questions